javascript - 如何从不同的 JS 文件中设置一行的状态?
问题描述
我用电子制作了 reactjs 应用程序。在应用程序上,其中一个页面上有一个表(table.js),其中的列都与状态无关。我正在通过主文件 App.js 渲染所有组件。但是我有一个 nodejs 脚本,其中包含一些请求。随着脚本的继续,我想更新 table.js 中每行一列的状态。我怎样才能做到这一点?
表.js:
<table>
<thead>
<tr>
<th>col1</th>
<th>col2</th>
<th>col3</th>
</tr>
</thead>
<tbody>
{rows.map((row,i) => {
return(
<tr>
<td>{i}</td>
<td>{task.task.Number}</td>
<td>{task.task.Place}</td>
<td>{row.row.Status}</td>
</tr>
);
})}
</tbody>
</table>
这是 nodejs 脚本(示例):
request.get(url, (err, resp, body) => {
*here is where I want to set the State of the status(col3) in Table.js*
})
在 App.js 中,这给出了我的构造函数的示例:
constructor(){
super();
this.state = {
render:'',
row: {
Number: '',
Place: '',
Status: '',
},
rows: []
}
}
请记住,所有文件都在 react-app 的 src 文件夹中。
解决方案
尝试将请求导入您的 App.js 并在那里使用它。您可以使用响应中的数据并在那里更新您的状态。
例如,在下面的代码中,您可以使用该getRow
方法来更新状态:
import request from 'request-library';
class App extends Component {
constructor(props) {
super(props);
this.state = {
render: '',
row: {
Number: '',
Place: '',
Status: '',
},
rows: []
};
}
getRow = async (rowToGet) => {
const response = await request.get(rowToGet);
this.setState({
rows: this.state.rows.map((row) => {
if (newRow.Number === row.Number) {
row.Status = newRow.Status;
}
return row;
})
});
}
render() {
<Table rows={this.state.rows} />
}
}
推荐阅读
- c# - 在 gRPC 中,无法将消息中的枚举值绑定到 dontnet core Dto
- node.js - 在一个简单的节点/反应应用程序中获取 Gitlab API 数据
- xaml - StringFormat 中的 Xamarin XAML 多语言
- c# - 通过 Ajax 请求超时 Umbraco Azure
- c - 异或运算的C程序,scanf输入的运算符
- meshlab - 向 Hausdorff 距离图添加图例
- javascript - 将 Array 转换为 String 再转换回 Array JavaScript 错误
- python - *(星号)可以作为文字字符传递给python吗
- mongodb - MongoTemplate聚合投影,映射数组属性时出现异常
- python - 即使通过虚拟环境安装了flask_wtf,我的程序也没有被执行