我正在获取数据并尝试使用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
答案 0 :(得分:1)
因为您要在返回的值中调用getRouteDirection()
,请改用useEffect
来调用getRouteDirection()
...
useEffect(() => getRouteDirection());
return (
<Fragment>
<select onChange={onChangeHandler}>
{routeOptions}
</select>
//some thing
</Fragment>
);
解释:getRouteDirection()
将在每次调用时更改状态,状态更改后将导致再次调用getRouteDirection()
,依此类推。