我处于无法在 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 需要一个参数 那么我该怎么办?,是否有我不知道的反应钩子?,是否有解决此问题的反应库?
答案 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>
);
}
发生了什么;