reactjs道具VS状态:未正确设置状态

时间:2019-10-20 20:25:01

标签: javascript reactjs

我正在尝试通过呈现帖子的循环添加无限滚动。 但是,我不断收到以下错误,即我的obj未定义。有人知道出了什么问题吗?

原始错误:

Uncaught TypeError: Cannot read property 'next' of undefined
    at Object.fetchMoreData [as next] (bundle.js:27529)
    at InfiniteScroll.onScrollListener (bundle.js:27932)
    at InfiniteScroll.<anonymous> (bundle.js:28093)
fetchMoreData @ bundle.js:27529
onScrollListener @ bundle.js:27932
(anonymous) @ bundle.js:28093

在构造函数中添加bind fetchMoreData()之后,原始错误消失了。但是我怀疑我的状态数据仍然设置不正确,因为我遇到以下错误。我试图登录控制台,但是什么也没显示...

bundle.js:27530 GET http://localhost:8000/undefined 404 (NOT FOUND)
fetchMoreData @ bundle.js:27530
onScrollListener @ bundle.js:27935
(anonymous) @ bundle.js:28096
localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

api如下。在这里,我跟踪了如果触发了无限滚动,我应该在页面上显示的接下来的事情的api URL。

{
  "next": "/api/v1/p/?size=1&page=2", 
  "results": [
    {
      "postid": 2, 
      "url": "/api/v1/p/2/"
    }
  ], 
  "url": "/api/v1/p/"
}

我的代码如下。我在fetchMoreData()中尝试了state和props,但是都没有用。


  constructor(props) {
    // Initialize mutable state
    super(props);
    this.state = { results: [], next: "", url: ""};
  }


  componentDidMount() {
    // Call REST API to get number of likes
    fetch(this.props.url, { credentials: 'same-origin' })
    .then((response) => {
      if (!response.ok) throw Error(response.statusText);
      return response.json();
    })
    .then((data) => {
      this.setState({
        results: data.results,
        next: data.next,
        url: data.url,
      });
    })
    .catch(error => console.log(error));
  }

  fetchMoreData() {

    fetch(this.props.next, {method: 'GET'})
    .then((response)=>{
      return response.json();
    })
    .then((data)=>{
      this.setState({
        results: this.state.results.concat(data.results),
        next: data.next,
      });
    });

  }

  render() {
    let has_more;
    if( this.state.next == '' ){
      has_more = false;
    } else {
      has_more = true;
    }


    return (
      <InfiniteScroll next={this.fetchMoreData} hasMore={has_more}>

      <ul> 
        {this.state.results.map((post)=> (
          <li><Post url={post.url}/></li>
        ))}
      </ul>
      </InfiniteScroll>


    );
  }


2 个答案:

答案 0 :(得分:0)

尝试一下:

fetchMoreData = () => {

    fetch(this.props.next, {method: 'GET'})
    .then((response)=>{
      return response.json();
    })
    .then((data)=>{
      this.setState({
        results: this.state.results.concat(data.results),
        next: data.next,
      });
    });

添加箭头功能时,您的this将指向当前类,您将可以访问propsstate

答案 1 :(得分:0)

由于使用的是类,因此需要绑定函数,使其具有正确的this

next={this.fetchMoreData.bind(this)}

然后,在fetchMoreData中使用this.state.next代替this.props.next