【发布时间】: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')
);
【问题讨论】:
-
它是否与:stackoverflow.com/questions/44312437/… 相关,历史对象必须从外部上下文中引用?
-
网址至少更新了吗?只是不重新渲染?
标签: javascript reactjs api react-props