当你的数据是同步的
差的:
数据来源是同步的,没有必要使用。
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
const str = localStorage.getItem('todos');
const items = JSON.parse(str) || [];
setTodos(items);
}, []);
return (
<>
{todos.map((item) => (
<>{item}</>
))}
</>
);
}
正确示例:
直接使用。
function App() {
const str = localStorage.getItem('todos');
const items = JSON.parse(str) || [];
const [todos, setTodos] = useState(items);
return (
<>
{todos.map((item) => (
<>{item}</>
))}
</>
);
}
当你的数据可以通过其他数据计算得来
差的:
const TOPICS = [
{
id: 1,
name: 'name-1',
},
{
id: 2,
name: 'name-2',
},
{
id: 3,
name: 'name-3',
},
];
function Topic({ selectTopicId }) {
const [selectedTopIC, setSelectedTopic] = useState(null);
useEffect(() => {
const targetItem = TOPICS.find((item) => item.id === selectTopicId);
setSelectedTopic(targetItem);
}, [selectTopicId]);
return (
<>
<div>selectedTopic: {selectedTopic}</div>
</>
);
}
更好的:
从已有数据中派生。
const TOPICS = [
{
id: 1,
name: 'name-1',
},
{
id: 2,
name: 'name-2',
},
{
id: 3,
name: 'name-3',
},
];
function Topic({ selectTopicId }) {
const selectedTopic = TOPICS.find((item) => item.id === selectTopicId);
return (
<>
<div>selectedTopic: {selectedTopic}</div>
</>
);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。