【问题标题】:Reactjs - better solution for setState inside fetchReactjs - setState 在 fetch 中的更好解决方案
【发布时间】:2020-11-21 03:27:42
【问题描述】:

这个问题基本解决了here但是有点过时了。

我试图在获取完成后设置状态。不幸的是,将 fetch 放入ComponentDidMount() 的基本解决方案没有按我的意愿工作(它表明状态未定义)所以我找到了这样的解决方案:声明全局变量,将获取的数据分配给这个全局变量,然后在@987654323 @做this.setState()。它有效,但我觉得这不是一个完全正确的解决方案。

有没有更好/更简洁的方法在 fetch 中执行 setState?

这是我的代码片段:

var fetchedData = null;

class Main extends Component {
    state = {
        data: "",
    };

    componentDidMount() {
        fetch("some-url", {
            credentials: "include",
        }).then((res) => {
            res.json()
                .then((data) => {
                    fetchedData = data;
                })
                .then(() => {
                    if (fetchedData.someData) {
                        this.setState({ data: fetchedData.someData });
                    }
                });
        });
    }
    //rest of code
}

【问题讨论】:

  • 这里使用全局变量是没有意义的。为什么不在json() 回调中使用setState
  • 我不确定如何实现这个回调。你能展示一下它的样子吗?

标签: javascript reactjs


【解决方案1】:

试试这个

class Main extends Component {
    state = {
        data: "",
    };

    async componentDidMount() {
        let res = await fetch("some-url", {credentials: "include"});
        let data = await res.json();
        if (data.someData) {
            this.setState({ data: data.someData });
         } 
        });
    }
    //rest of code
}

【讨论】:

    【解决方案2】:
    class Main extends Component {
        constructor(props) {
            super(props); 
            this.state = {
                data: ''
            }
        }
    
        componentDidMount() {
            fetch("some-url", {
                credentials: "include",
            }).then((res) => res.json())
              .then(data => this.setState({data}));
        }
        //rest of code
    }
    

    【讨论】:

    • 不幸的是它不起作用。这是我的基本解决方案,但在某些情况下,它显示状态为 undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多