gpt4 book ai didi

javascript - 如何在 react-router Route 中从 onChange 调用 dispatch?

转载 作者:行者123 更新时间:2023-11-30 00:10:11 25 4
gpt4 key购买 nike

我正在开发一个 Web 应用程序,我想在其中使用 URL 查询来运行搜索查询。
执行搜索时,应根据 url 查询参数向服务器发送新请求以获取新数据。
使用 react-routerRedux,我想调用 dispatch 函数根据查询(即 url)从服务器获取新数据改变)。

我正在考虑使用 onChange 事件并调用 dispatch 函数,如下所示:

<IndexRoute component={Catalog} onChange={(prevState, nextState, replace) => {dispatch(fetchProducts(nextState.location.search))}}/>

但是由于我的路由不是 React 组件,所以我无法访问调度功能。
我可以导入我的商店并使用 store.dispatch,但我不建议阅读它。
你会建议我做什么?

最佳答案

为了解决这类问题,我们总是在类似这样的函数中声明或路由:

function createRoutes(store) {
return {
component: App,
childRoutes: [
// Here are defined the other routes.
// They can be defined using plain objects:
{path: "profile", component: Profile},
// Or generated through a function call:
...require("./some/module")(store),
]
}
}

当您执行此操作时,使用商店来分派(dispatch)操作或在 React Router 生命周期 Hook 中进行计算是相当简单的。

function createRoutes(store) {
return {
component: Settings,
onEnter: (nextState, replace, callback) => {
const state = store.getState()
if (!state.user.logged) {
dispatch(createNotification("You must be logged to perform this"))
replace("/login")
}

callback()
}
}
}

关于javascript - 如何在 react-router Route 中从 onChange 调用 dispatch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com