首页 > 解决方案 > 如何从不同的 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 文件夹中。

标签: javascriptnode.jsreactjs

解决方案


尝试将请求导入您的 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} />
    }
}

推荐阅读