问题
I am trying to get the search results to display on another page in React Js. For now, when I submit my search form, it will display the results on the same page which I don't want. I have been trying to do this for the past 4 hours (I am new to ReactJS) and I have been seeing a lot of suggestions online but nothing seems to work as I was hoping.
I have even tried to use react redux, react router and much more example online but does not work, don't what I'm doing wrong.
How can I approach it? I would please like someone to probably put me on the right track in regards to the code I provide below and also your suggestions/feedback are welcome.
Thank you in advance.
Here is my search engine component responsible for the form
const SearchEngine = (props) => {
return (
<div>
<h3 className="spacer">Search Engine</h3>
<form onSubmit={props.getTrend}>
<div class="input-group md-form form-sm form-2 pl-0">
<input class="form-control my-0 py-1 red-border" type="text" name="keyword" placeholder="Enter your keyword" aria-label="Search" />
<div class="input-group-append">
<button class="input-group-text red lighten-3" id="basic-text1"><i class="fa fa-search text-grey" aria-hidden="true"></i></button>
</div>
</div>
</form>
</div>
);
}
export default SearchEngine;
and here is the result component where I would like to display the results
const Results = (props) => (
<div>
Hello
</div>
);
export default Results;
回答1:
After receiving your api calls you can throw a push and move to another page. For yours it may look something like this.
getTrend = async (e) => {
e.preventDefault();
const keyword = e.target.elements.keyword.value;
const api_call = await fetch(`http://localhost:8081/trend/twitter?keyword=${keyword}`); //make API call
const data = await api_call.json();
if (keyword) {
this.setState({
tweets: data
});
console.log(this.state.tweets);
this.props.history.push({
pathname: '/results',
state: { detail: data }
})
}
else {
this.setState({
tweets: undefined,
error: "Please enter the values"
});
}
}
Then, in your App.js you can access it with
props.location.state.detail
This may require that you use withRouter as a HOC. One thing I would change is grab your api in componentDidMount. However, it would be much easier if you went about this with hooks. While it may require some refractoring, you could make your api call with a hook, which is a ton simpler to get up and running.
来源:https://stackoverflow.com/questions/55668145/how-can-i-on-submit-my-form-redirect-the-results-to-another-page-in-react