簡體   English   中英

不能在反應中使用 useState 或 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>
    );
}

發生的事情是;

  • 一旦你的應用程序加載,並且組件沒有數據,options 被設置為一個空數組。 所以 map function 不會循環一次。
  • 數據是從父組件加載的。 觸發 useEffect 鈎子,重新加載組件(並運行 useEffect,您在此處設置新的 state 選項)
  • map 函數循環通過現在設置的選項 state

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM