我想使用钩子将状态设置为props,但出现错误:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
▶ 34 stack frames were collapsed.
我的代码: 第一个组件:
const List = () => {
const [items, setItems] = useState([{}])
useEffect(() => {
const fetchData = async () => {
const data = await fetch(
'http://localhost:5000/api',
);
const result = await data.json();
setItems(result);
};
fetchData();
}, []);
return (
<ActualList items={items}/>
)
}
和第二部分:
const ActualList = props => {
const [items, setItems] = useState([{}])
setItems(props.items)
}
...
答案 0 :(得分:1)
您可以将道具直接传递到useState
:
const ActualList = props => {
const [items, setItems] = useState(props.items) // pass props.items as an initial state
}
答案 1 :(得分:1)
您正在每个渲染器中调用setItem。每次更改状态值时,组件将被重新渲染,这将导致另一个状态更改,另一个重新渲染。...
您应该有条件地调用setItems
答案 2 :(得分:1)
所以我最终想出了如何做到这一点,以防有人需要,这里是代码:
const [items, setItems] = useState([{}]);
useEffect(() => setItems(props.items), [props])