繁体   English   中英

在React Native上获取请求后无法设置状态

[英]Unable to set state after fetch request on React Native

在使用fetch或axios(不能同时使用)执行GET请求后,尝试更改状态对象的值时,我遇到一个奇怪的问题。 我的代码很基本,我尝试了很多在线找到的解决方案,但是都没有用。

这是我到目前为止的代码...

class FilterScreen extends React.Component {

    state = {
        selectedCity: null,
        cities: [],
        selectedSpecialty: null,
        specialties: [],
    };


    componentWillMount() {
        this.fetchCities();
    }

    fetchCities = () => {

        fetch(`http://127.0.0.1:8000/app/cities`)
            .then(res => res.json())
            .then(e => {
                this.setState({
                    results: e.data.map(item => ({
                        label: item.name,
                        value: item.id
                    }))
                });
            })
            .catch(
                () => (
                    alert('There was an issue while fetching the doctors.')
                )
                );
        };

    render() {
        return (
          ... the body of the component...
            )}
}

export default FilterScreen;

我真的不明白我在做什么错。 我对React Native还是很陌生,也许这与生命周期有关,但是我敢肯定componentWillMount是正确的方法。 也许我错了。。。

您应该在componentDidMount进行异步调用。 请看这个

暂无
暂无

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

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