我试图渲染一个动态路由预加载通过异步 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
函数,它将接收存储(来自服务器)和props(来自客户端) . 不管怎样,应该通过redux / thunk获取类别 . 如您所见,我在通过服务器加载时没有传递动态 permalink
prop,因为我无法检索它 .
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
}
]
我并不完全确定我是以“标准”的方式做到这一点,但是这个过程在非动态路线上工作到目前为止 . 但是,我有一种感觉,我已经离开了基地:)
1 回答
在服务器上,您有请求对象,在客户端上,您有位置对象 . 检查当前环境后,从这些对象中提取url参数 .
现在,您将在桌面和服务器的initialAction中获取url . 你可以从中提取动态路线参数