首页 > 解决方案 > 如何避免使用 this.props 从另一个类中获取组件?(反应JS)

问题描述

所以我认为我的列表在添加新内容后没有更新,它只是覆盖列表然后开始从那里合并项目(以前会话中所有先前添加的数据在当前会话中第一次添加后消失) . 我希望保留旧数据,但我怀疑 this.props (在 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');

标签: reactjs

解决方案


推荐阅读