首页 > 解决方案 > How to refresh mapped table in React?

问题描述

I am rendering a table from mapped elements stored in the React state. However, the tr row elements are not rendered in the tbody component, even though console commands show the data is there. The code to render table rows from this.state.tableData is:

componentWillMount() {
    let data = this.props.dbPersons.get("directory");
    this.setState({ tableData: data });         
}

...

renderTableData() {
    return this.state.tableData.map((student, index) => {
      const { id, person } = student; 
      console.log("id'", id);
      console.log("person.lastName", person.lastName);

      return (
        <tr key={index}>
          <td>{id}</td>
          <td>{person.lastName}</td>
        </tr>
      )
    })
}

tbody is rendered if tableData is stored in the state:

{this.state.tableData && <tbody>
  {this.renderTableData()}
</tbody>}

But when the page is opened, the console displays the row data but tbody is rendered without any rows. Why? Does the component need to be refreshed somehow? Has the tbody component already been rendered and cannot be updated?

标签: javascriptreactjsreact-redux

解决方案


除了导致警告的 componentWillMount(将其替换为 compontDidMount)之外,到目前为止您发布的代码没有任何问题。我看不出它会记录但不渲染的原因。这是您的代码的工作示例:

class App extends React.Component {
  state = { tableData: false };
  componentWillMount() {
    setTimeout(
      () =>
        this.setState({
          tableData: [{ id: 1 }, { id: 2 }],
        }),
      500
    );
  }
  renderTableData() {
    return this.state.tableData.map((student, index) => {
      const { id } = student;
      console.log('id', id);
      return (
        <tr key={index}>
          <td>{id}</td>
          {/* <td>{name}</td> removed this but still can see id*/}
        </tr>
      );
    });
  }
  render() {
    return (
      <table>
        {this.state.tableData && (
          <tbody>{this.renderTableData()}</tbody>
        )}
      </table>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

也许你可以提供一个最小的例子来展示你正在经历的行为。


推荐阅读