如何避免使用this.props从另一个类获取组件? (ReactJS)

时间:2018-06-28 06:52:04

标签: reactjs

因此,我发现列表中添加了新内容后,列表并没有更新,只是覆盖了列表,然后从此处开始合并项目(先前会话中所有先前添加的数据在第一次添加后便消失了)。当前会话)。我希望保留旧数据,但我怀疑这是问题(在HTMLList类中)。

这是我的代码:

class HTML extends Component {
    constructor(props) {
    super(props);
    this.state = {
      html: [],
      description: "",
      body: ""
        };
    }
    componentDidMount() {
    db.onceGetHTML().then(snapshot =>
      this.setState(() => ({ html: snapshot.val() }))
    );
    }

  addContent(description, body) {
    this.setState({
      html: [
        ...this.state.html,
        {
          description: this.state.description,
          body: this.state.body
        }
      ] 
    });
        addAnHTML(this.state.description,this.state.body);
  }

  updateByPropertyName(property, e) {
    this.setState({
      [property]: e.target.value
    });
  }
  render() {
    const { html } = this.state;
    const { description } = this.state;
    const { body } = this.state;
    return (
      <div>
        <h1>Home</h1>
        <p>The Home Page is accessible by every signed in user.</p>
        <input
          value={description}
          onChange={this.updateByPropertyName.bind(this, "description")}
          type="text"
          placeholder="Description..."
        />
        <input
          value={body}
          onChange={this.updateByPropertyName.bind(this, "body")}
          type="text"
          placeholder="Body..."
        />
        <button onClick={this.addContent.bind(this)}>Add Content</button>
        {!!html && <HTMLList html={html} />}
      </div>
    );
  }
}

    /...../

class HTMLList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      description: '',
      BODY: '',
      desc: '',
      html: ''
    };
  }    
  render() {
    const { html } = this.props;
    const { desc } = this.state;
    const { BODY } = this.state;
    return (
      <div>

        <h2>List of HTML available:</h2>
        {Object.keys(html).map((key, index) =>

          <div key={index}>
            {index + 1}.
            {html[key].description}

            /....../

      </div>
    );
  }
}

编辑:(FIREBASE)这是我的getHTMLOnce()函数:

   export const onceGetHTML = () =>
    db.ref('Content').once('value');

0 个答案:

没有答案