反应useState导致渲染循环

时间:2019-12-09 20:08:12

标签: javascript reactjs infinite-loop

我正在获取数据并尝试使用const data = [{"name":"Animal care","Gap":"Above expectation","value":6},{"name":"Animal care","Gap":"At expectation","value":31},{"name":"Animal care","Gap":"Below expectation","value":18},{"name":"Calving and calf rearing","Gap":"Above expectation","value":8},{"name":"Calving and calf rearing","Gap":"At expectation","value":29},{"name":"Calving and calf rearing","Gap":"Below expectation","value":18},{"name":"Reproduction","Gap":"Above expectation","value":7},{"name":"Reproduction","Gap":"At expectation","value":25},{"name":"Reproduction","Gap":"Below expectation","value":23}] const result = data.reduce((r, o) => { const name = r[o.name] || (r[o.name] = {}) // create an object for the name, or use the existing one name[o.Gap] = (name[o.Gap] || 0) + o.value; // add/update the Gap value return r }, {}) console.log(result)挂钩将响应存储在状态中。当我从useState函数设置selectedRouteDirection时,渲染将在无限循环中运行。如何使用useState设置状态并仅渲染一次?

getRouteDirection

1 个答案:

答案 0 :(得分:1)

因为您要在返回的值中调用getRouteDirection(),请改用useEffect来调用getRouteDirection()

 ...

 useEffect(() => getRouteDirection());

 return (
        <Fragment>
            <select onChange={onChangeHandler}>
                {routeOptions}
            </select>
         //some thing 
        </Fragment>
    );

解释getRouteDirection()将在每次调用时更改状态,状态更改后将导致再次调用getRouteDirection(),依此类推。