gpt4 book ai didi

JavaScript 使用 async/await 确保我在实现之前检索值,但仍然返回 'undefined'

转载 作者:行者123 更新时间:2023-12-04 12:14:51 25 4
gpt4 key购买 nike

代码

async function getStudents() {
var reqObj = new RequestHandler("/students/all/");
let { students } = await reqObj.sendRequest();
console.log(students, students.length);
return students;
}

export default function Students(props) {
var students = getStudents();
return (
<main className="content-section">
<h1>Students</h1>
<span className="help-text">
You have {`${students.length}`} students.
</span>
</main>
);
}

...

export class RequestHandler {
// Base class for handling requests
constructor(url, method = "GET", contentType = "application/json") {
this.url = url;
this.method = method;
this.contentType = contentType;
this.request_conf = {
method: this.method,
url: this.url,
headers: {
"Content-Type": this.contentType,
"X-CSRFToken": cookies.get("csrftoken"),
},
credentials: "same-origin",
};
}
async sendRequest() {
const response = await axios(this.request_conf);
var data = isResponseOK(response);
return data;
}
}
console.log(students, students.length);getStudents() 内函数给了我预期的输出: [] 0 ,但是尽管试图使它成为一个异步函数, Students组件仍然得到 undefined作为值回来。
Students 中读取相同值的最简单方法是什么?零件?
免责声明
我是 JavaScript 的初学者,尤其是 Promises,所以如果我在这里遗漏了一些非常简单和/或明显的东西,请告诉我,不要对它有毒 :)

最佳答案

React 的“渲染”函数是一个同步的、纯函数。它不能等待值被呈现。这就是生命周期方法和状态的用途。
使用useState钩住 students状态数组和 useEffect使用空依赖数组进行 Hook 以调用 getStudents并等待 Promise 解决和排队状态更新并触发重新渲染。

export default function Students(props) {
// state to hold values
const [students, setStudents] = React.state([]);

// effect to fetch values
React.useEffect(() => {
getStudents().then(students => setStudents(students));
}, []); // <-- empty dependency == run once on component mount

return (
<main className="content-section">
<h1>Students</h1>
<span className="help-text">
You have {`${students.length}`} students.
</span>
</main>
);
}
文档
  • useState
  • useEffect

  • 如果您喜欢 async/await到 Promise 链:
    React.useEffect(() => {
    const fetchStudents = async () => {
    try {
    const students = await getStudents();
    setStudents(students);
    } catch(error) {
    // handle error, log it, etc...
    }
    };
    fetchStudents();
    }, []);

    关于JavaScript 使用 async/await 确保我在实现之前检索值,但仍然返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69341935/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com