问题
I am passing the date picked to the this.state.value Getting a time stamp of Midnight that day, but I can not seem to get it to render a new page so I can build the booking page. Where it takes the time stamp and checks for available times that day. When I did return the Handlesubmit on a half successful rerender I got a white page and back to the main app page with a blank date to choose again.
I have tried to build this as a functional component in the handleSubmit But also tried to return a component from the handleSubmit.
Here is the last failed to compile attempt and the last successful compile
handleSubmit(event) {
render(
{
const {bookingTime} = this.state.value;
if (bookingTime) {
return <Redirect to='/Bookingpage' />;
}
}
event.preventDefault();
}
This fail was from doing something similar to https://github.com/salsita/redux-form-actions/issues/2#issuecomment-318774722
While this is the half successful runs code (Just a White Blank page for about 1s)
handleSubmit(event) {
return <h1>{this.state.value}</h1>;
event.preventDefault();
}
This is the last Successful run on StackBlitz Check the components folder for and tool bar for files directly related to problem https://react-dnudvg.stackblitz.io/ Please note the code is there but its not building the app.
I expected for this run render a new page with one <h1>{this.state.value}</h1> as defined by the date picker
回答1:
It looks like the issue here is mixing up logic that should be rendered with logic that can go in an event handler method. In your first example, render is not a valid method that can be called from within handleSubmit, and in your second example, handleSubmit should not return components to be rendered.
You can get at your desired functionality by creating a state variable that indicates whether the user has submitted yet. Then you can check that variable when rendering (note that rendering is the return part of a functional component or the render method of a stateful component.
For example:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null, // for the date picker
wasSubmitted: false,
}
}
handleSubmit = event => {
event.preventDefault();
this.setState({wasSubmitted: true});
}
render() {
const { value, wasSubmitted } = this.state;
if (wasSubmitted) {
return <Redirect to='/Bookingpage' />
} else {
return //... your normal component
}
}
}
来源:https://stackoverflow.com/questions/56381473/in-jsx-how-to-redirect-on-handlesubmit-from-datapicker