首页 > 解决方案 > 在 React 中记录值

问题描述

我有 3 个组件。App.js - 主要。localLog.jsx 无状态,LoadBoard.jsx 有状态。我想从 LoadBoard 中获取数据字符串并将其显示在 localLog.jsx 中。问题是我无法弄清楚为什么 LocalLog 没有显示在屏幕上。

console.log(this.data.Array) in App.jsx localLog is ["configuration"] (2) ["configuration", "It's good configuration"]

应用程序.jsx

class App extends Component {
  constructor(props) {
    super(props);

    this.dataArray = [];
    this.state = {
      headers: []
    };
    this.localLog = this.localLog.bind(this);
  }

  localLog(data) {
    if (data) {
      this.dataArray.push(data);
      console.log(this.dataArray);
      this.dataArray.map(data => {
        return <LocalLog info={data} />;
      });
    }
  }

  render() {
    return (
      <>
        <LoadBoard apiBase={this.state.apiBase} localLog={this.localLog} />
        <pre id="log_box">{this.localLog()}</pre>
      </>
    );
  }
}

localLog.jsx

let localLog = props => {
  return (
    <pre className={classes.background}>
      <ul className={classes.ul}>
        <li>{props.info}</li>
        <li>hello world</li>
      </ul>
    </pre>
  );
};

export default localLog;

加载板.jsx

class LoadBoard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      positionToId: []
    };
  }

  componentDidMount() {
    this.props.localLog("configuration");
    this.props.localLog(`It's good configuration`);
  }

  render() {
    return (
      <div>
        <h1>Nothing interesting</h1>
      </div>
    );
  }
}

标签: javascriptreactjs

解决方案


您没有从该localLog方法返回任何内容,应该是:

return this.dataArray.map(data => {
    return <LocalLog info={data} />;
});

编辑:

这是您的 App 组件的外观。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      headers: [],
      logs: []
    };
    this.addLog = this.addLog.bind(this);
  }

  // Add log to state
  addLog(log) {
    this.setState(state => ({
      ...state,
      logs: [...state.logs, log]
    }));
  }

  render() {
    return (
      <>
        <LoadBoard apiBase={this.state.apiBase} localLog={this.addLog} />
        <pre id="log_box">
          {this.state.logs.map(log => {
            return <LocalLog info={log} />;
          })}
        </pre>
      </>
    );
  }
}

推荐阅读