【问题标题】:How to refresh React page/component on Button click after POST如何在 POST 后单击按钮上刷新 React 页面/组件
【发布时间】:2018-09-27 16:23:38
【问题描述】:

我希望在提交 POST 请求后按钮单击时刷新数据表。

我有一个反应按钮:

<Button onClick={this.click} className="domain-button" type='primary'>Add</Button>

以及对应的click函数,以及refreshPage函数:

async click() {
  const { domainInputValue } = this.state;
  console.log( domainInputValue );

  const response = await
  fetch('/new-cert', {
      headers: {
          'Content-Type': 'application/json'
      },

      method: 'POST',
      body: JSON.stringify({domainInput: domainInputValue})
  });

  const body = await response.text()
  console.log(body)

  if (response.status !== 200) throw Error(body.message);
  return body;
}

refreshPage() {
  window.location.reload();
}

在我的后端 Nodejs 中处理我的 POST 请求:

app.post('/new-cert', function (req, res) {
    fs.appendFile('certs-list', '\n' + req.body.domainInput, function (err) {
        if (err) throw err;
    });
    res.send('POST request: ');

    console.log("INSERTING")
    exec('sh cert-check-script-insert.sh');

    console.log(req.body);
    console.log('post is working!')
});

我不确定在哪里调用refreshPage(),我尝试在click() 之后立即调用它,但这似乎为时过早,并且刷新不会更改表格中显示的数据。

【问题讨论】:

  • 您可以在state 中有一个posted 变量,该变量在POST 之后会发生变化。这将导致组件重新渲染,这似乎是您想要的。
  • @Colin 谢谢你的建议,你能不能写一个答案,只是不知道把东西放在哪里

标签: javascript node.js reactjs refresh page-refresh


【解决方案1】:

延迟服务器响应,直到服务器准备好重新加载 - 在您的情况下,看起来您应该在 fs.appendFile 的回调中执行 res.sendexec。那么你的fetch 在服务器完全准备好之前不会解析,然后你重新加载。

刷新整个页面以获取新数据并不是很 React,但这不关我的事。

【讨论】:

  • 我应该重新渲染组件吗?如果可以的话,你能建议怎么做吗,对不起,我是新手
  • 是的,类似的。重新加载时新数据从何而来?
  • 也许您可以将新数据作为 POST 请求的响应发回并同时解决这两个问题。
  • 它来自一个后端 API,路径为 /list-certs,来自一个名为 certs.json 的本地文件。我尝试在fs.appendFile 调用certs-list 之后添加fs.readFile 调用certs.json,如果这就是你的意思吗?
  • 所以你的组件正在做另一个fetch 来获取数据?您应该能够让它再次这样做,而不是刷新所有内容。
【解决方案2】:

refreshPage() 调用放在await response.text() 之后:

async click() {
  const { domainInputValue } = this.state;
  console.log( domainInputValue );

  const response = await
  fetch('/new-cert', {
      headers: {
          'Content-Type': 'application/json'
      },

      method: 'POST',
      body: JSON.stringify({domainInput: domainInputValue})
  });

  const body = await response.text()

  refreshPage();

  console.log(body)

  if (response.status !== 200) throw Error(body.message);
  return body;
}

不过,我同意@ben-west 的观点——我建议使用state in React 来处理这个问题。从本质上讲,您将希望 setState 使用响应中您关心的任何数据,然后在组件中任何您需要的地方使用来自 this.state 的数据。

【讨论】:

  • 感谢您的回答,但这似乎是过早的重新加载,因为它不显示新数据,我必须再次重新加载才能显示。你能用States写一个答案吗?我是 React 和 Nodejs 的新手,但仍在努力理解它
【解决方案3】:

我最终添加了一个函数 componentDidUpdate(),它模仿了我的 componentDidMount() 行为:

componentDidMount() {
    this.callApi()
        .then(res => {
            this.setState({
                json: res.map(x => x),
            })
        })
        .catch(err => console.log(err));
}


componentDidUpdate() {
    this.callApi()
        .then(res => {
            this.setState({
                json: res.map(x => x),
            })
        })
        .catch(err => console.log(err));
}

【讨论】:

  • 如果您要复制这样的代码,我建议您将其提取到一个函数中并从componentDidUpdatecomponentDidMount 调用它。
猜你喜欢
  • 2014-01-20
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-21
  • 2014-04-10
  • 1970-01-01
相关资源
最近更新 更多