【问题标题】:Redirect to new page on Submit: this.props.history.push重定向到提交时的新页面:this.props.history.push
【发布时间】:2019-01-17 11:22:25
【问题描述】:

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

我使用 github jobs API 在 ComponentDidMount 中提取我的 API 数据。

我在表单上有一个 handleChange,当我输入职位搜索关键字时,它会返回职位结果。例如“开发人员”工作,在“纽约”。
这一切都有效。

不过,在提交时,我想将我的数据推送到一个新页面 - “工作结果”。就像您在正常的工作网站上看到的那样。输入职位搜索,结果会在新页面上加载。

我正在尝试使用 this.props.history.push 来推送我存储在 set 中的位置数据并将其返回到 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')
);

【问题讨论】:

标签: javascript reactjs api react-props


【解决方案1】:

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

【讨论】:

  • 谢谢,我会试试的。但是,在您的 中,我应该在 {/* ... */} 中添加什么? IE - 我应该在这里写什么代码?我很高兴自己试一试,我只是想知道你为什么把它留空。谢谢。
  • @ReenaVerma 不客气! {/* ... */} 只是让我的答案更简短的一种方式。 BrowserRouter 中的内容可以正常工作。
  • 嘿@tholle,我还没有机会接触它,抱歉 - 我只是需要优先考虑代码测试。今晚我肯定会玩得很快。 :( 。我一使用它就会告诉你。给我几个小时 - 谢谢 :)
  • 嘿@Tholle - 很抱歉延迟回复您。这是疯狂的几周,但这非常有效!谢谢!! :)
猜你喜欢
  • 2016-01-09
  • 2021-01-03
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多