【发布时间】:2024-05-19 02:20:02
【问题描述】:
我创建了一个自定义挂钩来对返回对象数组的 rest 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];
}
【问题讨论】:
标签: react-native axios use-state