React笔记系列(一)
提示:Raect列表数据获取,渲染与状态提升,工程列表
文章目录
前言
提示:用于参考和学习React写法
可以了解到React目录结构、组件组合、数据传递、useEffect、useState。
提示:以下是本篇文章正文内容,主要分为菜单结构,代码正文。文件部分列举,App.tsx,src/screens/project-list目录下index.jsx、list.jsx、search-panel.jsx
一、项目结构(图片)
二、项目文件代码
1.App.tsx
代码如下(示例):
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { ProjectListScreen } from "screens/project-list";
function App() {
return (
<div className="App">
<header className="App-header">
<ProjectListScreen />
</header>
</div>
);
}
export default App;
2.src/screens/project-list目录
2.1 index.jsx
代码如下(示例):
import { React } from "react"
import { SearchPanel } from "./search-panel"
import { List } from "./list"
import { useState, useEffect } from "react"
import { cleanObject } from "utils"
import * as qs from "qs"
const apiUrl = process.env.REACT_APP_API_URL
export const ProjectListScreen = () => {
const [param, setParam] = useState({
name: '',
personId: ''
})
const [list ,setList] = useState([])
const [users, setUsers] = useState([])
useEffect(() => {
fetch(`${apiUrl}/porjects?${qs.stringify(cleanObject(param))}`).then(async response => {
if(response.ok) {
setList(await response.json())
}
})
}, [param])
useEffect(() => {
fetch(`${apiUrl}/users`).then(async response => {
if(response.ok) {
setUsers(await response.json())
}
})
}, [])
return <div>
<SearchPanel param={param} setParam={setParam} users={users} />
<List list={list} users={users} />
</div>
}
2.2 list.jsx
代码如下(示例):
import { React } from "react"
export const List = ({list, users}) => {
return <table>
<thead>
<tr>
<th>名称</th>
<th>负责人</th>
</tr>
</thead>
<tbody>
{
list.map(project => <tr key={project.id}>
<td>{project.name}</td>
<td>{users.find(user => user.id === project.personId)?.name || '未知'}</td>
</tr>)
}
</tbody>
</table>
}
2.3 search-panel.jsx
代码如下(示例):
import { React } from "react"
// import { useState, useEffect } from "react";
export const SearchPanel = ({param, setParam, users}) => {
return <form>
{/* setParam(Object.assign({}, param, {name:evt/target.value})) */}
<input type="text" value={param.name} onChange={evt => setParam({
...param,
name: evt.target.value
})} />
<select value={param.personId} onChange={evt => setParam({
...param,
personId: evt.target.value
})}>
<option value={''}>负责人</option>
{
users.map(user => <option key={user.id} value={user.id}>{user.name}</option>)
}
</select>
</form>
}
总结
提示:这里对文章进行总结:
通过一个小的demo了解基础的React写法,后续继续学习记录笔记,自我成长。
版权声明:本文为cyril_96原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。