我创建了一个自定义钩子,以异步调用rest api,该api返回对象数组。我有两种异步方法。第一个方法返回对象列表。在成功的休息呼叫中,状态数组[dataEntry]得到更新,但是在第二次呼叫中,后一个请求返回单个对象。当我尝试将新返回的对象添加到状态数组[dataEntry]时,看不到添加到数组的新对象。
import { useState, useContext } from 'react';
import restApi from '../api/restApi';
import { Context as AuthContext } from '../context/AuthContext';
export default () => {
const { state } = useContext(AuthContext);
const [lastPage, setLastPage] = useState(true);
const [nextPageNumber, setNextPageNumber] = useState(0);
const [dataEntry, setDataEntry] = useState([]);
const [errorMessage, setErrorMessage] = useState(null);
const [dataUpdate, setDataUpdate] = useState(false);
const getAllData = async (pageNumber, pageSize) => {
try {
restApi.get('/data/list', {
headers: {
Authorization: 'Bearer ' + state.tokenData,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response.data.result);
setLastPage(response.data.lastPage);
setNextPageNumber(response.data.nextPageNumber);
setDataEntry([...response.data.result]);
setDataUpdate(true);
})
} catch (error) {
console.log(error.response.data);
}
}
const createData = async ({ dataName }) => {
try {
console.log('creating data ' + dataName);
restApi.post(
"/data", {
dataName
}, {
headers: {
Authorization: 'Bearer ' + state.tokenData,
'Content-Type': 'application/json'
}
}).then(response => {
console.log(response.data);
console.log(dataEntry.length)
setDataEntry([...dataEntry, response.data]);
console.log(dataEntry.length)
setDataUpdate(true);
})
} catch (error) {
console.log(error.response.data);
}
}
return [getAllData, createData, dataEntry, lastPage, nextPageNumber, dataUpdate];
}
答案 0 :(得分:0)
由于您要根据先前的状态更新状态dataEntry
,因此请将回调函数传递给setDataEntry
。另外,请确保传播prev
状态并合并响应结果。
getAllData函数
...
setDataEntry(prev => [...prev, ...response.data.result]);
...
createData函数
...
setDataEntry(prev => [...prev, ...response.data]);
...
此外,在createData
函数中,console.log(dataEntry.length)
将不会输出最新结果,因为状态更新是异步的。