我希望将api调用的结果显示在“ /事件”页面上。我尝试过使用从react-router-dom重定向,但这仅重定向页面。
我试图看这个答案
How can I on Submit my Form redirect the Results to another Page in React
但是不确定如何将其应用于我的代码。如果我使用this.props.history.push('/ events'),则会收到一条错误消息,提示它无法识别.push。
如果有人可以让我走上正确的道路,将不胜感激。
import React, {Component} from 'react';
import axios from 'axios';
import {Form, FormControl, Button} from 'react-bootstrap';
import './style.css';
class SearchField extends Component {
state = {
search: ""
};
handleChange = (event) => {
const {name, value} = event.target;
this.setState({[name]: value.toLowerCase()});
};
apiCall = () =>{
const corsAnywhere = "https://cors-anywhere.herokuapp.com/";
const ticketmasterURL = "https://app.ticketmaster.com/discovery/v2/events/?keyword=";
const searchKey = process.env.REACT_APP_TM_KEY;
const term = this.state.search.split(" ").join("+");
axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
.then(res => {
console.log(res.data._embedded.events);
this.history.push("/events");
})
.catch(err => console.log(err));
};
handleSubmit = (event) => {
event.preventDefault();
this.apiCall();
};
render(){
return (
<div className="search-container">
<Form onSubmit={this.handleSubmit}>
<Form.Group>
<FormControl
type="text"
placeholder="Search"
name="search"
value={this.state.search}
onChange={this.handleChange}
/>
<div className="btn-container">
<Button type="submit">Submit</Button>
</div>
</Form.Group>
</Form>
</div>
)
}
}
export default SearchField;
答案 0 :(得分:1)
使用this.props.history.push('/events')
时出现错误。
由于要使用history
对象,因此需要使用withRouter
HOC包装组件。
import { withRouter } from 'react-router-dom';
class SearchField extends Component { ... }
export default withRouter(SearchField)
现在您可以使用history
对象发送数据了,
axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
.then(res => {
console.log(res.data._embedded.events);
this.props.history.push({
pathname: '/events',
state: { events_data: JSON.stringify(res.data._embedded.events) }
})
})
在events
组件中,您可以访问如下数据,
render(){
const events_data = JSON.parse(this.props.location.state.events_data)
console.log(events_data)
return( ... )
}
您还可以使用react-router-dom
包中的Redirect
发送数据。
axios.get(corsAnywhere + ticketmasterURL + term + "&apikey=" + searchKey)
.then(res => {
console.log(res.data._embedded.events);
<Redirect
to={{
pathname: '/events',
state: { events_data: JSON.stringify(res.data._embedded.events) }
}}
/>
})
在events
组件中,您可以访问如下数据,
render(){
const events_data = JSON.parse(this.props.location.state.events_data)
console.log(events_data)
return( ... )
}