JavaScript 使用 async/await 确保我在实现之前检索值,但仍然返回“未定义”

W1c*_*k3d 4 javascript async-await reactjs

代码

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

函数console.log(students, students.length);内部getStudents()给出的输出正如我所期望的:[] 0,但尽管尝试使其成为异步函数等,Students组件仍然得到undefined返回值。在组件中读取相同值的最简单方法是什么Students

免责声明

我是 JavaScript 的初学者,尤其是 Promises,所以如果我在这里遗漏了一些非常简单和/或明显的东西,请告诉我,不要对此有毒:)

Dre*_*ese 5

React 的“渲染”函数是一个同步的纯函数。它不能等待值被渲​​染。这就是生命周期方法和状态的用途。

使用useState钩子将数组保持students在状态中,并使用useEffect具有空依赖项数组的钩子来调用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>
  );
}
Run Code Online (Sandbox Code Playgroud)

文档

如果您更喜欢async/awaitPromise 链:

React.useEffect(() => {
  const fetchStudents = async () => {
    try {
      const students = await getStudents();
      setStudents(students);
    } catch(error) {
      // handle error, log it, etc...
    }
  };
  fetchStudents();
}, []);
Run Code Online (Sandbox Code Playgroud)

  • 在您编写的代码的 async/await 版本中,我不是必须编写 ```const Students = wait getStudents();``` 吗? (2认同)
  • @W1ck3d 啊,是的,完全可以。抱歉,‍♂️ 这是一个复制/粘贴错误,我以某种方式删除了通话的“await”。感谢您的关注。 (2认同)