React 中的表单提交

Form submission in React

我正在尝试在 React 中提交表单。此表单是 connected one,因此表单数据将作为道具出现。我想要实现的是当 props are different 时应该自动提交表单,这意味着对于一组道具,表单应该只自动提交一次。

我尝试在 componentWillReceiveProps 中添加一个条件,我也可以在其中确定道具是否不同,提交表格。最初,this.propscomponentWillReceiveProps

的第一次渲染中未定义
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = { formSubmitted: false }
  }
  componentWillReceiveProps(nextProps) {
    if (this.props.picmonicVideoData.data.signature !== nextProps.picmonicVideoData.data.signature) {
      this.setState({formSubmitted: false});
  }
  componentDidUpdate = () => {
    if (!this.state.formSubmitted) {
      this.setState({ formSubmitted: true })
      document.getElementById('ltiLaunchForm').submit()
    }
  } 
  render() {
    let renderInputFields = null
    if (this.props.videoData.data.hasOwnProperty("signature")) {
      renderInputFields = Object.keys(launchData).map((key, i) => {
        return (<input type="hidden" name={key} key={i} value={launchData[key]} />)
      })
    }
    return (
      <div>
        <iframe width="100%" height="430px" frameBorder="0" name="videoIframe"></iframe>
        <form name="ltiLaunchForm" id="ltiLaunchForm" method="post" target="target_iframe" encType="application/x-www-form-urlencoded" action={launchUrl}>
          {renderInputFields}
          <input type="hidden" name="oauth_signature" value={signature} />
        </form>
      </div>
    )
  }
}

如有任何帮助,我们将不胜感激。

我在此建议仅使用 componentDidUpdate,因为您可以轻松比较 prevProps 和当前的 props 并执行提交操作。所以你的代码看起来像这样:

componentDidUpdate = (prevProps) => {
    if (this.props !== prevProps) {
      document.getElementById('ltiLaunchForm').submit()
    }
  }

如果您计划使用 React 16.3 及更高版本,您将不再需要 componentWillReceiveProps 并避免使用 React 中已弃用的生命周期。有关详细说明,请查看此 link.