如何解决:setState在gastby中不起作用?

时间:2019-11-03 02:57:50

标签: reactjs gatsby

我正在使用gatsby进行服务器端渲染。

这是我的代码:

class BookSearch extends Component {

    state = {
        search: '',
        books: '',
    };

    componentDidMount() {
        this.loadData()
    }

    loadData () {
        axios.get('/books/list')
            .then(response => {
                this.setState({books: response.data.books});
                console.dir(response.data.books);
            })
            .catch(error => {
                this.setState({error: true});
            });
    }

不幸的是,this.setState在gatsby中不起作用。加载页面时未调用componentDidMount。我该怎么办?

3 个答案:

答案 0 :(得分:1)

我认为您应该有一个错误?这是因为您尚未初始化error状态。您必须先初始化状态,然后才能使用它们:

state = {
   search: '',
   books: '',
   error: false
};

我希望这可以解决问题。否则,我在您的代码中看不到任何问题。

答案 1 :(得分:1)

您提到您正在使用SSR? 在这种情况下,请尝试使用componentWillMount,因为在SSR中未调用componentDidMount

如果您使用的是React版本> 16.3:

  

在支持服务器渲染时,当前需要同步提供数据-componentWillMount通常用于此目的,但可以使用构造函数代替。即将发布的暂挂API将为客户端和服务器渲染提供完全干净的异步数据获取功能。

参考:https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data

对于您而言,我认为使用getInitialProps静态方法会更有意义。 (https://nextjs.org/learn/basics/fetching-data-for-pages/fetching-batman-shows

如果您对SSR不太熟悉,那么Next.js会提供出色的教程: https://nextjs.org/learn/basics/getting-started

这可能会帮助您!

答案 2 :(得分:1)

我认为问题在于将this绑定到loadData方法。

您可以通过两种方式绑定它。

  1. 在构造函数中绑定this
constructor(props){
   super(props)
   this.state = {
        search: '',
        books: '',
    }
    this.loadData = this.loadData.bind(this)  //Bind this here
}
  1. 或者您可以简单地使用箭头功能,
loadData = () => { //Arrow function auto binds `this`
   axios.get('/books/list')
   .then(response => {
        this.setState({
           books: response.data.books
        }); 
        console.dir(response.data.books);
   })
   .catch(error => {
      this.setState({error: true});
   });
}
相关问题