[英]Why React doesn't render my result after setState?
Having the below jsx code: 具有以下jsx代码:
import React, { Component } from 'react';
import RemoteAssets from '../modules/RemoteAssets';
class RemoteOptions extends Component {
constructor(props) {
super(props);
this.state = {
RemoteOptions: []
}
}
componentDidMount() {
const { api, locale } = this.props;
RemoteAssets.loadRemoteOptions({ api, locale }).then((RemoteOptions) => {
console.log( 'RemoteOptions', RemoteOptions);
this.setState((state, props) => ({
RemoteOptions
}), () => {
this.render()
});
})
}
render() {
return (
<div className="row">
<div className="col-4">
<label >Opt: </label>
</div>
<div className=" col-8">
{JSON.stringify(this.state.RemoteOptions)}
</div>
</div>
);
}
}
export default RemoteOptions;
This is what happens to me: 这是发生在我身上的事情:
componentDidMount logs correctly the payload expected. componentDidMount正确记录了预期的有效负载。
console.log( 'RemoteOptions', RemoteOptions);
So I believe that It will also set State as expected: 因此,我相信它也会使State达到预期的状态:
this.setState((state, props) => ({
RemoteOptions
}), () => {
this.render()
});
I also added above a this.render() stmt to be sure the component will be re-rendered after updating the state. 我还添加了一个this.render()stmt,以确保在更新状态后将重新呈现该组件。
But : 但是:
{JSON.stringify(this.state.RemoteOptions)}
Will always return "[]" as the init state before componentDidMount happens and update the state. 在componentDidMount发生并更新状态之前,将始终返回“ []”作为初始状态。
How should I arrange this component to have my render update the with the payòoad loaded async? 我应该如何安排该组件以使我的渲染更新与异步加载的payòoad?
Your state name and class name are in conflict. 您的州名和班级名冲突。
class RemoteOptions extends Component { // class name
constructor(props) {
super(props);
this.state = {
RemoteOptions: [] // state name
}
}
...
Call your state something different. 称您的州不同。
Why not simply using setState the way documentation suggests? 为什么不按照文档建议的方式简单地使用setState?
this.setState({ RemoteOptions });
Render method will be automatically called right after the state is set. 设置状态后,将立即自动调用渲染方法。
I implemented the skeleton of the problem, and everything works as expected. 我实现了问题的框架,一切都按预期进行。
const loadRemoteOptions = () => new Promise(resolve => { setTimeout(() => resolve('myRemoteOptions'), 1000) }) class App extends React.Component { state = { remoteOptions: null } componentDidMount(){ loadRemoteOptions().then(remoteOptions => this.setState({ remoteOptions })) } render(){ return this.state.remoteOptions || 'Loading...'; } } ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.