我正在加载初始加载的数据。当用户点击按钮添加识别时,api调用会添加并返回它。我将新的post添加到数组中,但新的更新不会呈现。返回对象和对象数组是相同的对象类型。当我重新加载页面时,会呈现新的帖子,只是不在add函数上。有什么东西我遗漏了吗?
const [recognitions, setRecognitions] = useState([]);
useEffect(() => {
Api.GetRecognitions(params)
.then(response => {
const items = response || [];
setRecognitions(recognitions => [...recognitions, ...items]);
})
}, [setRecognitions]);
const handleAddPost = () => {
Api.AddRecognition(params)
.then(response => {
const newPost = response;
setRecognitions(recognitions=> [...recognitions, newPost])
});
}
<Form.Group>
<Form.Field>
<Button basic color='blue' onClick={handleAddPost}>Add</Button>
</Form.Field>
</Form.Group>
<Form.Group>
<Form.Field>
{recognitions.map(recognition => (
<RecogWallPost
key={recognition.recogStagingId}
recognition={recognition}
participantId={participantId}
/>
)
)}
</Form.Field>
</Form.Group>
您希望传递[recognitions]
,而不是传递[setRecognitions]
作为useEffect
的第二个参数。这告诉useEffect
钩子在每次识别更改时运行,它在handleAddPost
中这样做。
您必须创建一个异步函数,然后按如下方式使用它:
useEffect(() => {
async function initData() {
Api.GetRecognitions(params)
.then(response => {
const items = response || [];
setRecognitions(recognitions => [...recognitions, ...items]);
})
}
initData()
}, [setRecognitions]);