我使用history.push("/"(从另一个页面重定向到我的主页,主页有一个ProjectList组件,它发送一个操作:
App.js
function App(){
return(
<Router>
<NavBar></NavBar>
<Switch>
<Route
path="/createProject"
component={withAuthentication(CreateProjectPage)}
></Route>
<Route
exact
path="/"
component={withAuthentication(HomePage)}
></Route>
</Switch>
</Router>
);
}
export default App
创建项目页面
function CreateProject(){
const dispatch = useDispatch();
const history = useHistory();
const submitHandler = (e) => {
...
dispatch(createNewProject({...}));
history.push("/");
}
return (
<div>
...
<Button
onClick={submitHandler}
variant="contained"
color="primary"
>
Submit
</Button>
</div>
)
}
主页
export default function HomePage(props){
return (
<div>
<ProjectList level="one"/>
...
</div>
);
}
项目列表组件:
export default function ProjectList({level}){
console.log(level); //onRedirect, this gets called
const dispatch = useDispatch();
useEffect(() => {
console.log("dispatch returnAllProjects called") //onRedirect, this does not get called
dispatch(returnAllProjects());
}, [dispatch]);
...
return ...
}
仅在刷新时调用此returnAllProjects。这会导致获取未定义的对象。
如有任何帮助,我们将不胜感激!
如果您希望在重定向后调用效果,则应添加location
作为依赖项:
import { useLocation } from 'react-router-dom';
export default function ProjectList({level}){
const location = useLocation(); // <--- listen to location
const dispatch = useDispatch();
useEffect(() => {
dispatch(returnAllProjects());
}, [dispatch, location]); //<--- location is added as dependency
...
return ...
}