提交时重定向到新页面:this.props.history.push

Redirect to new page on Submit: this.props.history.push

我正在尝试构建一个简单的工作板,ReactJS 前端。

我正在使用 github 个作业 API 将我的 API 数据拉入 ComponentDidMount。

我在表单上有一个 handleChange,当我输入工作搜索关键字时,它会产生 returns 个工作结果。例如 "developer" 个职位,在 "new york".
这一切都有效。

虽然在提交时,我想将我的数据推送到新页面 - "job results"。就像您在普通求职网站上看到的那样。输入职位搜索,结果会加载到新页面上。

我正在尝试使用 this.props.history.push 将我存储在集合中的位置数据和 return 推送到包含 url“/jobresults”的页面。

虽然这不起作用。我没有收到错误。什么也没发生,我的页面保持原样。

我做错了什么?这是我的 app.js 代码。

谢谢, 瑞娜

import React from 'react';
import axios from 'axios';
import ReactDOM from 'react-dom';
import Header from './components/Header';
import Navbar from './components/Navbar';

import Jobs from './components/Jobs';
import HomePageResults from './components/HomePageResults';
import JobResults from './components/JobResults';
import JobDescription from './components/JobDescription';
import ApplyNow from './components/ApplyNow';
import Confirmation from './components/Confirmation';
import './assets/scss/main.scss';

import { BrowserRouter, Route, Switch } from 'react-router-dom';



class App extends React.Component {

  constructor() {
    super();
    console.log('CONSTRUCTOR');

    this.state = {
      jobs: [],
      searchData: '',
      cityData: 'new york',
      locations: []
    };
  }



  // FUNCTION TO CALL API IS WORKING
  componentDidMount() {
    console.log('Component Did Mount: WORKING');
    axios.get('https://jobs.github.com/positions.json?search=')

      .then(res => {
        console.log(res.data.slice(0,4));
        this.setState({ jobs: res.data.slice(0,4) });
      });
  }


  // HANDCHANGE FOR JOB SEARCH
  handleChange = (e) => {
    console.log(e.target.value);
    this.setState({ searchData: e.target.value });
  }


  // HANDLE CHANGE FOR LOCATION SEARCH
  handleChangeLocation = (e) => {
    console.log('location', e.target.value);
    this.setState({ cityData: e.target.value });
  }


  // HANDLE SUBMIT
  handleSubmit = (e) => {
    e.preventDefault();
    console.log(this.state.searchData);
    axios.get(`https://jobs.github.com/positions.json?description=${this.state.searchData}&location=${this.state.cityData}`)


      .then(res => {
        this.setState({ locations: res.data });
        console.log('location data', this.state.locations);
      })
      .then(() => this.props.history.push('/jobresults'));
  }



  render() {
    return(


      <main>
        <BrowserRouter>
          <section>
            <Navbar />

            <Switch>
              <Route path="/jobs" component={Jobs} />
              <Route path="/jobresults" component={JobResults} />
              <Route path="/jobdescription" component={JobDescription} />
              <Route path="/apply" component={ApplyNow} />
              <Route path="/confirmation" component={Confirmation} />
            </Switch>

            <Header
              handleChange={this.handleChange}
              handleChangeLocation={this.handleChangeLocation}
              handleSubmit={this.handleSubmit}
            />
            <HomePageResults jobs={this.state.jobs}/>
          </section>
        </BrowserRouter>

      </main>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

route props 仅在提供给 Route 组件的组件中可用,因此您不能在 App 组件中使用 this.props.history

您可以改为手动创建 history 对象并将其提供给 Router,这样就可以在您认为合适的地方使用 history 对象。

import { Router, Route, Switch } from "react-router-dom";
import createHistory from "history/createBrowserHistory";

const history = createHistory();

class App extends React.Component {
  // ...

  handleSubmit = e => {
    e.preventDefault();
    axios
      .get(
        `https://jobs.github.com/positions.json?description=${
          this.state.searchData
        }&location=${this.state.cityData}`
      )
      .then(res => {
        this.setState({ locations: res.data });
        history.push("/jobresults");
      })
      .catch(error => console.log(error));
  };

  render() {
    return (
      <main>
        <Router history={history}>{/* ... */}</Router>
      </main>
    );
  }
}