简体   繁体   English

React setState 两次呈现状态

[英]React setState twice renders state

When I trade with setState, it turns twice.当我使用 setState 进行交易时,它会转两次。 First the Data Fail is returned and then the Data Ready is returned.首先返回数据失败,然后返回数据就绪。 Console return false first then true.控制台先返回 false,然后返回 true。 I just want to return true in the console.我只想在控制台中返回 true。

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            data: []
        };
    }
    componentDidMount() {
        fetch("https://reqres.in/api/users?page=2")
            .then(res => res.json())
            .then(result => {
                this.setState({
                    data: result.data,
                    loading: true
                });
            });
    }
    render() {
        const { loading } = this.state;
        console.log(loading);
        const dataReady = <div>Data Ready </div>;

        const DataFail = <div>Data Fail </div>;
        return <div>{loading === true ? dataReady : DataFail}</div>;
    }
}

Example: https://codesandbox.io/s/kopz8wrl7o示例: https : //codesandbox.io/s/kopz8wrl7o

It is due to the React's lifecycle and the fact that you are setting the state.loading property initially to false.这是由于 React 的生命周期以及您最初将 state.loading 属性设置为 false 的事实。 https://reactjs.org/docs/react-component.html https://reactjs.org/docs/react-component.html

First there is the initial render, then the componentDidMount with its setState is called.首先是初始渲染,然后调用带有 setState 的 componentDidMount。 You might want to leave the loading undefined and then in the render method check if its defined or not before checking its value.您可能希望保持加载未定义,然后在渲染方法中检查它是否已定义,然后再检查其值。

You simply reversed the boolean associated with the loading.您只需反转与加载相关的布尔值。 You should initially set it to true and then to false when your data is loaded.您应该最初将其设置为true ,然后在加载数据时将其设置为false

Working example :工作示例:

 class App extends React.Component { constructor(props) { super(props); this.state = { loading: true, error: false, data: [] }; } componentDidMount() { fetch("https://reqres.in/api/users?page=2") .then(res => res.json()) .then(result => { this.setState({ data: result.data, loading: false }); }) .catch(error =>{ this.setState({ error: true }); }); } render() { const { loading, error } = this.state; !loading && console.log(true) return <div>{!loading && <div>Data Ready </div>} {error && <div>Data Error :( </div>} </div>; } } ReactDOM.render(<App/>, document.getElementById('root'))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.1.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.1.1/umd/react-dom.production.min.js"></script> <div id='root'/>

your data changes that's why you have two messages:您的数据发生变化,这就是为什么您有两条消息: 在此处输入图片说明

you need did decision, what's you gonna do?你需要做决定,你会怎么做? if you didn't want change state you can use shouldComponentUpdate , or you can just skip 1 console message如果您不想更改状态,您可以使用shouldComponentUpdate ,或者您可以跳过 1 条控制台消息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM