【发布时间】:2017-09-09 02:16:15
【问题描述】:
我正在尝试呈现一个动态路由,该路由预加载了通过异步 thunk 获取的数据。
我的组件中有一个静态initialAction 方法需要预加载,并让它们根据需要调用操作。完成所有操作并解决承诺后,我会渲染路线/页面。
我的问题是:如何在静态函数中引用路由参数和/或道具?
这里是相关代码,它将调用可能需要预加载数据的任何 initialAction 函数。
const promises = routes.reduce((promise, route) => {
if (matchPath(req.url, route) && route.component && route.component.initialAction) {
promise.push(Promise.resolve(store.dispatch(route.component.initialAction(store))))
}
return promise;
}, []);
Promise.all(promises)
.then(() => {
// Do stuff, render, etc
})
在我的组件中,我有静态的initialAction 函数,它将在商店(来自服务器)和道具(来自客户端)中获取。一种或另一种方式,应该通过 redux/thunk 获取类别。如您所见,我在通过服务器加载时没有传递动态 permalink 属性,因为我无法检索它。
class Category extends Component {
static initialAction(store, props) {
let res = store !== null ? getCategory(REACT_APP_SITE_KEY) : props.getCategory(REACT_APP_SITE_KEY, props.match.params.permalink)
return res
}
componentDidMount(){
if(isEmpty(this.props.category.categories)){
Category.initialAction(null, this.props)
}
}
/* ... render, etc */
}
最后,这是我正在使用的路线:
import Home from '../components/home/Home'
import Category from '../components/Category'
import Product from '../components/product/Product'
import NotFound from '../components/NotFound'
export default [
{
path: "/",
exact: true,
component: Home
},
{
path: "/category/:permalink",
component: Category
},
{
path: "/:category/product/:permalink",
component: Product
},
{
component: NotFound
}
]
不完全确定我什至是以“标准”方式执行此操作,但到目前为止,此过程在非动态路由上有效。但是,我有一种感觉,我已经离开基地了 :)
【问题讨论】:
标签: reactjs redux server-side redux-thunk