无法从React中的子组件更改父状态

时间:2019-03-01 12:01:10

标签: reactjs

我正在构建一个简单的聊天应用程序,但是不显示从子组件的输入字段中发布的新评论。 -父组件-

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      comments: [],
      currentUser: { displayName: "user3", uid: 3 }
    };
  }

  addComment = comment => {
    this.setState(prevState => {
      comments: prevState.comments.push(comment);
    });

    console.log("this.state");
    console.log(this.state);
  };

  render() {
    const { comments, currentUser } = this.state;
    return (
      <div className="App">
        {comments.map(comment => (
          <div className="line__left" key={comment.createdAt}>
            <figure>
              <i className="fas fa-user fa-4x" />
            </figure>
            <div className="line__left-text">
              <div className="name">{comment.createdBy.displayName}</div>
              <div className="text">{comment.text}</div>
            </div>
          </div>
        ))}

        <ChatInputBox addComment={this.addComment} currentUser={currentUser} />
      </div>
    );
  }
}

-子组件-

class ChatInputBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "",
      currentUser: this.props.currentUser
    };
  }
  handleChange = e => {
    this.setState({ text: e.target.value });
  };
  handleClickPost = e => {
    e.preventDefault();
    let comment = {
      createdAt: new Date().getTime(),
      createdBy: this.state.currentUser,
      text: this.state.text
    };
    this.props.addComment(comment);
    this.setState({ text: "" });
  };

  render() {
    const { text } = this.state;
    return (
      <div className="ChatInputBox">
        ChatBox
        <textarea onChange={this.handleChange} value={text} />
        <button onClick={this.handleClickPost}>Post</button>
      </div>
    );
  }
}

在我填充文本区域并单击按钮之后,父对象的状态似乎已更新,但是未显示新注释。如何显示它?

1 个答案:

答案 0 :(得分:1)

更改代码

set -eo pipefail;{command}

  addComment = comment => {
    this.setState(prevState => {
      comments: prevState.comments.push(comment);
    });

    console.log("this.state");
    console.log(this.state);
  };

使用 addComment = comment => { const { comments } = this.state; this.setState({ comments: comments.concat(comment) }); }; 时,请使用setState()而不是concat,因为这样可以保持数组的不变性。