不能在反应中使用 useState 或 useEffect 我还有什么?

时间:2021-02-26 04:19:53

标签: javascript arrays reactjs react-hooks

我处于无法在 React 中使用 useState 或 useEffect 的位置。如果我使用 useState 它会触发无限渲染我不能使用 useEffect 因为我需要状态来做某事。

示例:

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 函数需要一个参数“index”我不能直接使用 useEffect 因为我不认为 useEffect 需要一个参数 那么我该怎么办?,是否有我不知道的反应钩子?,是否有解决此问题的反应库?

1 个答案:

答案 0 :(得分:0)

useEffect 可以处理,你需要将你想检查数组变化的状态作为 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 函数不会循环一次。
  • 数据是从父组件加载的。触发 useEffect 钩子,重新加载组件(并运行 useEffect,您在此处设置选项的新状态)
  • 地图函数循环到现在设置的选项状态
相关问题