javascript - 在 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>
);
}
}
解决方案
您没有从该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>
</>
);
}
}
推荐阅读
- apache-spark - 什么时候使用 UDF 与使用 spark 功能比较合适?
- julia - 使用 Julia 安装 GMT 包时出现问题
- typescript - 类型兼容性
- javascript - 在浏览器中运行代码时如何定义需求?
- javascript - 身份验证的 URL 重定向
- c# - 使用 Linq 按字典顺序排列列表
- python - 如何在我的 discord.py 机器人中创建有效的介绍功能?
- amazon-web-services - HIVE_BAD_DATA:解析字段值 JSONObject 时出错,无法转换为 Int
- spring - 它的好做法是我自己的安全逻辑吗?
- firebase - exportVal() 和 val() firebase 之间的区别?