0

你好,由于某种原因,React 不会全局更新状态,

  componentDidMount() {
    var id = window.location.href.split('/')[3]
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "https://reactAppBackend/edit/" + id);
    xhr.send();
    xhr.onloadend = () => {
      this.setState({singlePost: JSON.parse(xhr.responseText)})
      console.log(this.state.singlePost[0])
    };
  }

当我运行这个控制台日志返回数据这个数据

{_id: "5e6016adb8c32b00883f55f5", postTitle: "RE4", postContent: "the best ", __v: 0}

但是当我尝试渲染状态时:

  render() {
    return (
      <div>{this.state.singlePost[0]}</div>
    )
  }

它没有渲染任何东西。

4

3 回答 3

0

状态是一个数组,我已经设法使用 map 函数显示响应。

  render() {
    return (
      <div>
        {this.state.singlePost.map(post => {
          return (
            <div>
              <p>{post.postTitle}</p>
              <p>{post.postContent}</p>
              <img src={post.postPicturePath} />
            </div>
          );
        })}
      </div>
    );
  }
于 2020-03-19T13:49:29.120 回答
0

你的渲染中有一个错字。应该是 singlePost


render() {
    return (
      <div>{this.state.singlePost[0]}</div>
    )
  }
于 2020-03-18T12:43:52.197 回答
0

你这里有一个错字:<div>{this.state.siglePost[0]}</div>

singlePost,应该是 singlePost

于 2020-03-18T12:43:54.403 回答