ReactJS:无法通过异步函数外部的二维数组进行解析
ReactJS: Unable to parse through a 2d array outside async function
尝试在异步函数中设置数组的状态,并在异步函数中访问它工作正常。但是当我尝试在异步函数之外访问它时,它只通过第一层解析意味着 bookDetails[0],而解析 bookDetails[0][0] 给出了一个错误 "cannot-read-property-0-of-undefined"
getAll = async () => {
const { contract } = this.state;
const response = await contract.methods.getBooks().call();
this.setState({ bookDetails: response});
console.log("books: ",this.state.bookDetails[0][0]);
};
//OUTPUT=> books: nanme
//console.log outside the async function gives error
请注意 setState 本身并不同步,您必须在其回调中检查更新后的状态:
getAll = async () => {
const { contract } = this.state;
const response = await contract.methods.getBooks().call();
this.setState({ bookDetails: response}, () => console.log("books: ",this.state.bookDetails[0][0]);
);};
除此之外,该代码段不足以验证您无法正确登录的外部异步功能的原因。请提供更完整的代码段。
尝试在异步函数中设置数组的状态,并在异步函数中访问它工作正常。但是当我尝试在异步函数之外访问它时,它只通过第一层解析意味着 bookDetails[0],而解析 bookDetails[0][0] 给出了一个错误 "cannot-read-property-0-of-undefined"
getAll = async () => {
const { contract } = this.state;
const response = await contract.methods.getBooks().call();
this.setState({ bookDetails: response});
console.log("books: ",this.state.bookDetails[0][0]);
};
//OUTPUT=> books: nanme
//console.log outside the async function gives error
请注意 setState 本身并不同步,您必须在其回调中检查更新后的状态:
getAll = async () => {
const { contract } = this.state;
const response = await contract.methods.getBooks().call();
this.setState({ bookDetails: response}, () => console.log("books: ",this.state.bookDetails[0][0]);
);};
除此之外,该代码段不足以验证您无法正确登录的外部异步功能的原因。请提供更完整的代码段。