在React中提交表单

时间:2018-11-25 20:10:58

标签: javascript reactjs redux

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

我尝试在componentWillReceiveProps中添加一个条件,也可以在其中确定道具是否不同,然后提交表单。最初,this.props的第一个渲染中未定义componentWillReceiveProps

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>
    )
  }
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我建议在此仅使用componentDidUpdate,因为您可以轻松比较prevProps和当前props并执行提交操作。因此您的代码应如下所示:

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

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

相关问题