我是一个新的反应,所以也欢迎指点。
我正在用api调用的json填充一个数组:
fetch('/rpa').then(rpa => rpa.json()).then(data => data.rpa).then(nestedData=>nestedData.forEach(item => jsonRespnse.push(item)));
console.log(jsonRespnse)如我所料,登录到控制台会显示数据。但是,将该数据作为返回的一部分放入,我什么也得不到:
return (
<div>
{rpaName.map((rpaItem, i) => (
<div>
<div className='headerContainer' onClick={()=>toggle(i)}>
<h4 className='rpaHeader'>{rpaItem}</h4><span className='rpaSpan'>{selected === i ? '-': '+'}</span>
</div>
<div className={selected === i ? 'rpaButton show': 'rpaButton'}>
<button onClick={()=>sendData(rpaItem)}>Start{rpaItem}</button><button>Stop{rpaItem}</button>
</div>
<br></br>
</div>))}
</div>);}我假设这是一个计时问题,渲染发生在数组可以填充之前,当我硬编码一个数组时,它工作得很好。
如果有人能给我指出正确的方向,我将不胜感激。
发布于 2021-06-23 22:11:32
由于您使用的是函数式组件,因此可以在呈现组件之前使用react的useEffect钩子执行API调用。
然后,您可以使用useState挂钩声明一个状态变量来保存获取的数据。
示例代码:
import React, { useState, useEffect } from 'react';
const yourComponent = () => {
const [ data, setData ] = useState([]);
useEffect(() => {
fetch('<URL>').then(response => response.json()).then(responseArr => setData(responseArr)));
}, []);
return(
//Rest of the code (Now you can use the fetched data as an array since "data" state's been populated with the data fetched from the API call)
);
}发布于 2021-06-23 22:22:36
在组件内部重新渲染的唯一方法是使用state。
在React的世界中,由于您没有提供完整的组件,我假设您使用的是函数式组件,其中有useState和useEffect等钩子。
useState是您将更改变量放入的位置。
举例说明。
function MyComponent() {
// the first variable here is the actual value of the state, the next is the function to change the state.
const [myState, setMyState] = React.useState();
// when we move over to useEffect, is the hook that'd typically use to perform fetch requests for example.
React.useEffect(() => {
fetch(...).then(response => response.json()).then(setMyState);
}, [])
return <div>{myState}</div>
}当状态获得新值时,它将重新呈现组件以反映新的更改。
发布于 2021-06-23 22:11:43
您可能希望将请求数组设置为状态对象,例如
import React, { useState } from 'react';
function someReactComponent() {
// Declare a new state variable, which we'll call "count"
const [fetchResponse, setFetchResponse] = useState([]);
fetch('/yourfetchurl').then(response => response.json()).then(responseArr => setFetchResponse(responseArr)));
return (
<div>
{fetchResponse.map((res, i) => {
return (
<div key={i}>
{res.whatever}
</div>
);
})}
</div>
);
}
https://stackoverflow.com/questions/68101417
复制相似问题