javascript - render 会在 setState 之后立即被调用吗?

标签 javascript reactjs

我有以下功能:

onSelectDepartment = (evt) => {
    const department = evt.target.value;
    const course = null;

    this.setState({ department, course });

    this.props.onChange({ name: 'department', value: department });
    this.props.onChange({ name: 'course', value: course });

    if (department) this.fetch(department);
};

问题是,setState函数调用后,组件上的render函数是立即执行还是函数调用结束后执行?

最佳答案

render function on the component will be executed immediately or after function call is finished?

没有人能保证渲染函数何时会被调用,因为 setState 是异步的,当我们调用 setState 时意味着我们要求 React 使用新的状态值更新 ui(请求调用渲染方法),但确切地说什么时候会发生,我们永远不知道。

看看是什么react doc says about setState :

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

查看此答案以获取有关 setState 的异步行为的更多详细信息:Why calling setState method doesn't mutate the state immediately?

关于javascript - render 会在 setState 之后立即被调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48880548/

相关文章:

javascript - 如何将 hashmap 值从 java 文件传递​​到 Javascript

Javascript:当字符串连接时,新的正则表达式会破坏 for 循环迭代器

javascript - 在javascript中需要帮助包装函数并正确处理 "this"

javascript - 使用 Flowrouter 和 trackerreact 显示来自 Meteor.call 函数的数据。

javascript - 在同一个 js 文件中使用 React 和 React Native 库

javascript - 提交按钮会删除 Material ui 表中的所有复选框

javascript - Bootstrap 文本区域在 Firefox 中呈现奇怪且丑陋的效果

javascript - 如何使用元素的实时宽度同时调整另一个div的大小?

reactjs - 具有编辑模式和查看模式的 React 组件,这是正确的模式吗?

javascript - ReactJS 可以在 Bootstrap 中返回 div 吗?