下一个js不更新URL

时间:2019-05-28 10:12:13

标签: javascript next.js

我有以下内容:

import React, {Component} from "react";
import fetch from 'isomorphic-unfetch';
import {Router} from '../routes';

class About extends Component {
  state = {
    results: null,
    postcode: null
  }

  handleOnChange = e => {
    this.setState({
      postcode: e.target.value
    });
  }

  handleOnSubmit = e => {
    e.preventDefault();
      // calling the api passing the postcode
      console.log(this.state.postcode)
    fetch(`http://localhost:3001/${this.state.postcode}`)
      .then(response => response.json())
      .then(data => {
          this.setState({
            results: data
          })
      })
      .catch(error => console.error(error))

      Router.pushRoute('/about', {postcode: this.state.postcode})
  }

  render() {
    console.log(this.state.results)
   return(
    <form>
      <input name="postcode" onChange={this.handleOnChange} />
      <button onClick={this.handleOnSubmit}>submit postcode</button>
    </form>
   )
  }
}

About.getInitialProps = async function(context) {
  console.log('context: ', context.query)
  return {
    results: 'data'
  }
}

export default About;

和我的路线文件如下:

const routes = module.exports = require('next-routes')()

routes
.add('index')
.add('about', '/about/:postcode', 'about');

但是,当我提交表单时,我希望URL可以像这样提交的值进行更新:

http://localhost:3000/about/ => http://localhost:3000/about/postcodeValueSubmitted

它不会引发任何错误,但URL仍然存在:

http://localhost:3000/about

我需要更新值,以便可以使用'getInitialProps'进行服务器端渲染。

2 个答案:

答案 0 :(得分:0)

替换:

Router.pushRoute('/about', {postcode: this.state.postcode})

使用:

Router.pushRoute(`/about/${this.state.postCode}`)

答案 1 :(得分:0)

这有助于:

Router.pushRoute('about', {postcode: this.state.postcode})

请注意不带'/'

的区别