【发布时间】: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