【问题标题】:React Native state isn't changingReact Native 状态没有改变
【发布时间】:2018-05-06 03:23:58
【问题描述】:

我正在向返回一些电影的 Json 文件发出 Ajax 请求。

    state = { movies: [] };

    componentWillMount()
    {
        this.getMovies();
    }

    /*
       Make an ajax call and put the results in the movies array
     */
    getMovies()
    {
        axios.get('https://pastebin.com/raw/FF6Vec6B')
            .then(response => this.setState({ movies: response.data }));
    }



    /*
        Render every movie as a button
     */
    renderMovies()
    {
        const { navigate } = this.props.navigation;

        return this.state.movies.map(movie =>
            <ListItem key={ movie.title }
                title={ movie.title }
                icon={{ name: 'home' }}
                onPress={() =>
                    navigate('Details', { title: movie.title, release: movie.releaseYear })
                }
            />
        );
    }

    render() {
        return(
            <List>
                { this.renderMovies() }
            </List>
        );
    }

我得到的错误如下:this.state.map 不是函数。这是因为电影仍然是空的。

当我 console.log response.data 它返回 JSON 文件中的所有行。所以问题很可能出在这一行:

.then(response => this.setState({ movies: response.data }));

有人知道出了什么问题吗?

【问题讨论】:

标签: javascript json reactjs react-native


【解决方案1】:

你把初始状态放在了错误的地方。改为这样做:

constructor(props) {
   super(props);
   this.state = { movies: [] };
}

来自document

一般来说,你应该在构造函数中初始化state,然后 想要更改时请致电setState

【讨论】:

    【解决方案2】:

    更新你的ajax请求如下:

    /*
       Make an ajax call and put the results in the movies array
     */
    getMovies()
    {
        let self = this;
        axios.get('https://pastebin.com/raw/FF6Vec6B')
            .then(response => self.setState({ movies: response.data }));
    }
    

    另外,你可以在构造函数中绑定你的函数:

    constructor(props){
      super(props);
      this.getMovies = this.getMovies.bind(this);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-08
      • 2020-05-03
      • 2019-03-22
      • 2019-09-23
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 2022-07-06
      • 2018-01-09
      相关资源
      最近更新 更多