如何使用 React 更改 Promise 中的页面

How to change page in a Promise using React

我正在使用 Reactjs。我有一个表单,它将仅使用名称 属性 填充我的数据库 onSubmit。假设插入数据成功,我如何跳回到我在承诺中的登陆页面?我的目标网页 url 是一个简单的“/”。或者我应该跳回到其他地方的登陆页面而不是在承诺中。

const React = require('react')
const axios = require('axios')

class AddNewRecordLabel extends React.Component {
  constructor (props) {
    super(props)
    this.state = ({
      artists: []
    })
    this.onSubmit = this.onSubmit.bind(this)
  }
  componentDidMount () {
    axios.get('http://localhost:5050/recordLabels')
    .then((res) => {
      this.setState({
        artists: res.data
      })
    })
  }
  onSubmit (e) {
    e.preventDefault()
    if (!this.refs.name.value) {
      console.log('fill in the name input')
    } else {
      var object = {
        name: this.refs.name.value
      }
      axios.post('http://localhost:5050/recordLabels', object)
      .then((res) => {
        //change here
      })
    }
  }
  render () {
    return (
      <div>
        <h3>add new record label</h3>
        <form onSubmit={this.onSubmit}>
          <label>
            <input type='text' ref='name' placeholder='name'/>
          </label>
          <br></br>
          <button type='submit'> Add Record Label </button>
        </form>
      </div>
    )
  }
}

module.exports = AddNewRecordLabel

通常,您会使用通量模式创建一个库,该模式使用调度程序、操作和存储来控制您的组件。如果你想节省很多时间,可以使用 flux 模式的库,例如 react-redux 和 react-flux。

我以前使用过自制的通量模式。我现在正在使用 redux,它非常易于使用,而且根据我的个人经验可以快速开发。它有很好的文档和来自社区的大量支持。

如果您想保持简单,您可能需要重新考虑您的策略,例如 return发送消息来替换表单,为他们提供返回主页或什至离开表单等选项所以他们有机会添加另一个唱片公司。您还想检查是否有错误,并根据响应显示某种消息说明失败的原因。如果您想返回主页,只需将此添加到您的承诺中...

window.location.href = '/'

...但理想情况下,您希望将服务调用移动到另一个文件和 return 响应,然后相应地对组件中的这些响应进行操作,但一般推荐的方法是通过调度程序和侦听器并在此组件中更新您的状态或道具。