【问题标题】:Update the url and save the axios response更新 url 并保存 axios 响应
【发布时间】:2020-08-10 00:52:44
【问题描述】:

我有我的代码来接受用户的输入(设备名称),一旦我点击 View ,我就会向服务发送一个 axios 请求并从中获得响应,并使用该响应,我展示了一个设计设备名称。 此功能运行良好。

 <input type="text" id="devicename" onChange={this.onInputChange.bind(this)}><br> />
 <Button text='View' variant='primary' type='submit' onClick={this.onDeviceNameEntered} />

单击查看按钮时,将调用 onDeviceNameEntered,我发送的位置

onDeviceNameEntered = async () => {
    this.setState({ enteredDeviceName: true });
    const DeviceName = this.state.devicename;
    // an axios post request is built by calling buildRequestToGetData(DeviceName) 
    const responsedata = await axios.request(buildRequestToGetData(DeviceName)).then((response) =>
      (response.data),
    ).catch((error) => {
      if (error.response && error.response.data) {
        this.setState({ error: true });
      }
    }
    );
  //code to display the data in responsedata
  };

如果我需要从当前 url 更改 url: https://www.example.com/https://www.example.com/DeviceName 在获得输入设备名称的axios响应后,这样当我与其他人共享url时,他将能够看到特定设备的响应数据,而无需输入设备名称并再次单击提交按钮。 即,如果我需要更新我的 url 并且需要在获得响应后共享 url。有没有什么函数可以帮助我在 Javascript 中做到这一点?

【问题讨论】:

  • 你在使用 React 路由器吗?
  • 不,因为我的应用程序中只有一个网页,所以我没有使用 React 路由器。此外,单击查看按钮后,它会在同一页面中显示响应数据。

标签: javascript reactjs url redirect axios


【解决方案1】:

您可以使用window.location.pathname检查网址的路径名。

在您的示例中,将返回 /DeviceName。从路径名字符串中删除正斜杠,并将路径名设置为状态中的设备名。

state= {
 devicename: removeForwardSlash(window.location.pathname)
}

removeForwardSlash 只是一个实现删除正斜杠或解析路径名的函数,但最适合您。

使用 componentDidMount 检查设备名称是否存在于状态中,然后使用 this.state.devicename 进行 api 调用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 2021-11-14
    • 2020-04-21
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    相关资源
    最近更新 更多