有人可以解释为什么我的重定向返回空白页。该URL会更新,但是componentDidMount
不会触发,并且呈现的页面完全空白。
路径:App.js
class App extends Component {
componentDidMount() {
store.dispatch(loadUser());
}
render() {
return (
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" render={() => <Redirect to="/login" />} />
<PrivateRoute exact strict path="/mypage/:id">
<POForm />
</PrivateRoute>
</Switch>
</Router>
</Provider>
);
}
}
路径:PrivateRoute.js
const PrivateRoute = ({ children, auth, ...rest }) => {
if (auth.isLoading) return null;
return (
<Route
{...rest}
exact
strict
render={({ location }) =>
auth.isAuthenticated ? (
children
) : (
<Redirect
to={{
pathname: '/login',
state: {
from: location
}
}}
/>
)
}
/>
);
};
路径:POForm.js
class POForm extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
newId: ''
};
this.createNewPurchaseOrder = this.createNewPurchaseOrder.bind(this);
}
componentDidMount() {
axios
.get(`${process.env.REACT_APP_API_URL}/get/po`, {})
.then((res) => {
const purchaseOrder = middlewarePurchaseOrder(res.data);
purchaseOrder.isLoading = false;
this.setState(purchaseOrder);
})
.catch((err) => {
console.log('err', err);
});
}
createNewPurchaseOrder() {
axios
.post(`${process.env.REACT_APP_API_URL}/new/po`)
.then((res) => {
const po = res.data;
po.newId = res.data._id;
this.setState(po);
})
.catch((err) => {
console.log('err', err);
});
}
render() {
if (this.state.newId) {
return <Redirect to={`/mypage/${this.state.newId}`} />;
}
if (this.state.isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<button
type="button"
onClick={() => {
this.createNewPurchaseOrder();
}}
>
createNewPurchaseOrder
</button>
<p>Page has loaded.</p>
</div>
);
}
}