如何从其他JS文件设置行的状态?

时间:2018-08-13 02:04:46

标签: javascript node.js reactjs

我用电子制作了reactjs应用。在该应用程序上,其中一个页面上有一个表(table.js),其中各列的状态各不相同。我正在通过主文件App.js渲染所有组件。但是我有一个nodejs脚本,该脚本遵循一些请求。随着脚本的进行,我想更新table.js中每行列之一的状态。我该如何实现?

Table.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文件夹中。

1 个答案:

答案 0 :(得分:0)

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