我有以下功能:
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/