【问题标题】:Cannot use useState or useEffect in react what else do I have?不能在反应中使用 useState 或 useEffect 我还有什么?
【发布时间】:2021-02-26 04:19:53
【问题描述】:

我处于无法在反应中使用 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 需要一个参数 那我该怎么办?,有没有我不知道的反应钩子?,有没有解决这个问题的反应库?

【问题讨论】:

  • 我正在构建一个测验游戏,rendeBody 函数显示测验选项
  • 如果你想查看完整的代码,我在这里做了一些简化:gist.github.com/JunedKhan101/d86cab022fd1858e21c64a37b5c9eab7
  • 我的组件收到的道具是来自测验组件的“数据”
  • 您能清楚地解释您要达到的目标以及问题所在。以便我们可以帮助您。 在您的情况下,无限渲染是因为更新了渲染中的状态
  • 我不知道您需要什么,但您可以在 repo 中查看完整代码:github.com/JunedKhan101/Quiz-game

标签: javascript arrays reactjs react-hooks


【解决方案1】:

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,您在此处设置选项的新状态)
  • 地图函数循环进入现在设置的选项状态

【讨论】:

  • 如果 props.data 没有改变,那么这个 useEffect 只会被调用一次,对吗?
  • 最终组件加载了两次,因为 props.data 正在更改,因为您从父组件分配它。
  • 但这不起作用,因为 useEffect 需要访问索引
  • 什么意思,你说的这个索引是什么?你的价值观的指数?还是处于某种状态?
  • useEffect(() =&gt; { var temp = []; temp.push(props.data.results[index].correct_answer); props.data.results[index].incorrect_answers.forEach((current) =&gt; temp.push(current)); var arr = shuffle(temp); setOptions(options =&gt; arr); }, [props.data]); 索引显然是未定义的
猜你喜欢
  • 2021-09-06
  • 2020-10-21
  • 2023-02-01
  • 2023-01-17
  • 2019-10-14
  • 2019-04-12
  • 2021-04-19
  • 2022-01-06
  • 2021-11-13
相关资源
最近更新 更多