【问题标题】:Next.js Shallow Routing from Textinput Form Submit来自 Textinput 表单提交的 Next.js 浅路由
【发布时间】:2018-12-03 05:43:17
【问题描述】:

我在 Next.js 和 React 方面相对较新,

我想根据here中的Next.js示例在提交的表单中设置基于textinput状态的浅url。

尝试修改它以使用表单:

  render() {
    const {initialText, router} = this.props
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }

但我仍然无法将 this.state.value 传输到 handleSubmit 上的 { router } / this.props,因此它将显示在浏览器路由中...

如果有人可以提示继续..谢谢..

其余代码大致模仿示例:

  static getInitialProps({ res }) {
    if (res) {
      return { initialText: 'none' }
    }
      text = this.state.value;
    return {
        initialText: text
    }
  }

    constructor (props) {
        super(props);
        this.state = {value: 'none'};
    }

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

  handleSubmit = (event) => {
    const { router } = this.props

    const currentText = router.query.text
      ? router.query.text
      : 'none'
    const href = `/?text=${currentText}`
    Router.push(href, href, { shallow: true })
  }

【问题讨论】:

  • 请粘贴handleSubmit和handleChange的代码
  • 好的,更新代码..
  • 你把它定义为组件还是页面?
  • 我需要将其定义为浅路由,因此必须在同一页面中,我不知道是否可能

标签: javascript reactjs forms routes next.js


【解决方案1】:

为了能够使用getInitialProps(),您需要使用这是页面,因为它不适用于子组件。因此,如果您在子组件中使用 getInitialProps(),您的 initialText 将始终未定义。在子组件中,需要使用componentDidMount(),并在状态中设置initialText

因此,考虑到您已在页面、文件夹中定义了此组件,它应该可以工作。但是,如果您将以下内容定义为子组件,则它将不起作用。

static getInitialProps({ res }) {
    if (res) {
      return { initialText: 'none' }
    }
      text = this.state.value;
    return {
        initialText: text
    }
  }

    constructor (props) {
        super(props);
        this.state = {value: 'none'};
    }

  handleChange = (event) => {
    this.setState({ value: event.target.value });
  }

  handleSubmit = (event) => {
    const { router } = this.props

    const currentText = router.query.text
      ? router.query.text
      : 'none'
    const href = `/?text=${currentText}`
    Router.push(href, href, { shallow: true })
  }

【讨论】:

  • 我的意思是,在示例链接中,您也可以从路由中更改状态,我尝试将其插入 componentDidMount 但没有运气
猜你喜欢
  • 2021-10-17
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多