![](/img/trans.png)
[英]Should I import useState and useEffect or is it ok to use React.useState and React.useEffect?
[英]Cannot use useState or useEffect in react what else do I have?
我在 position 中,我不能在反應中使用 useState 或 useEffect 。 如果我使用 useState 它會觸發無限渲染我不能使用 useEffect 因為我需要 state 來做某事。
例子:
export default function MyApp(props) {
const [options, setOptions] = useState([]);
const renderBody = (index) => {
var temp = [];
temp.push(props.data.results[index].correct_answer);
props.data.results[index].incorrect_answers.forEach((current) => temp.push(current));
var arr = shuffle(temp); // shuffle is a function that shuffles array elements I need to shuffle only once but this shuffles elements every render
setOptions(options => arr); // this triggers infinite render I need this to be in useEffect(() => {}, [])
return (<div>{arr.map((value) => { <p>{value}</p> })}</div>);
}
return (
<div className="main">
{props.data.results.map((value, index) => {
{renderBody(index)}
})}
</div>
);
}
因為 renderBody function 需要一個參數“索引”我不能直接使用 useEffect 因為我不認為 useEffect 需要一個參數所以我該怎么辦?,有沒有我不知道的反應鈎子?,有解決這個問題的反應庫?
useEffect 可以處理,您需要通過 state 作為 useEffect 的第二個參數來檢查數組中的更改
export default function MyApp(props) {
const [options, setOptions] = useState([]);
useEffect(function(){
//this execute once the props.data changes
},[props.data]);
}
return (
<div className="main">
{options.map((value, index) => {
/*make sure you include the index in an element*/
})}
</div>
);
}
發生的事情是;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.