我对reactjs有点陌生,我正在一步一步地学习。我面临一个问题,那就是当我尝试访问 props 中的位置参数时,它返回undefined
。我试图找到解决方案,但大多数人都写过我必须在路由器中添加我的组件,但我将其包装在路由器中,但我仍然无法访问位置参数
export const abcdContainer = withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(abcd));
我正在尝试访问 和 组件中的位置参数,但问题是其中没有位置参数。有人可以告诉我出了什么问题
如果有人知道出了什么问题,请告诉我,我已经花了半天时间了,但我无法弄清楚
添加了 URL 的代码和版本
路由器版本 => 2.8.1
网址:http://localhost:3000/somePage?someParam=cm9oYW5qYWxpbHRlYWNoZXJAZ21haWwuY29t
abcdContainer.js
const mapStateToProps = (state, ownProps) => {
// some code over here
}
const mapDispatchToProps = (dispatch, ownProps) => {
// some code over here
};
export const abcdContainer = withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(abcd));
abcd.jsx
class abcd extends Component {
constructor(props, context) {
super(props, context);
this.state = {
// setting state over here
};
}
abcdFunction(){
if (this.props.location.query.someParam !== undefined){ // trying to extract someParam value from location
// some code over here
}
}
render() {
// some code over here
}
}
export default CSSModules(abcd, styles, { allowMultiple: true });
这是流程。路由器重定向到容器,然后容器重定向到真正的组件
Route.js
export const Routes = ({ store }) => (
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={aContainer}>
<IndexRoute component={IContainer} />
// some routes
<Route path="/openAbcd" component={() => (<abcdContainer caller="aaaaaaa" />)} />
// some routes
</Route>
// some routes
</Router>
</Provider>
);
Routes.propTypes = {
store: React.PropTypes.object.isRequired,
};
最佳答案
<Route path="/openAbcd" component={() => (<abcdContainer caller="aaaaaaa" />)} />
如果您使用内联箭头函数来渲染组件,为什么不直接将 props 传递给组件?那么你就不需要 withRouter()
。像这样:
<Route path="/openAbcd" component={props => (<abcdContainer caller="aaaaaaa" {...props} />)} />
Also the docs of react-router
v2.8.1 says about withRouter()
:
A HoC (higher-order component) that wraps another component to provide props.router.
它不提供location
但是router
作为 Prop 。我建议您更新react-router
到 v4 或至少 v3。
编辑:“但是为什么没有隐式插入 Prop ?”:
React 知道两种类型的组件。 Stateless functional components and class-based components 。函数组件是接受单个 props
的函数。带有数据的对象参数并返回一个 React 元素。再次查看这行代码:
<Route path="/openAbcd" component={() => (<abcdContainer caller="aaaaaaa" />)} />
您传递了一个箭头函数() => (<abcdContainer caller="aaaaaaa" />)
给您<Route>
element 是一个函数组件的内联定义,它采用 props
作为参数并返回渲染的 React 元素,在本例中这是您的 <abcdContainer>
。但正如您所看到的,您通过使用空括号定义函数中省略了 props 参数:() => (<AComponent />)
。 React 不会自动将 props 传递给在功能组件内渲染的子组件。包装您的 <abcdContainer>
时进入内联函数组件时,您负责自己将 props 传递给它。
但是如果您将基于类/功能组件的类/变量传递给 component
你的支柱<Route>
就像您在其他路由中所做的那样,它会渲染该组件并隐式传递 props 给它,因为它没有包装在功能组件中:
// this will directly render <aContainer> and pass the props to it
<Route path="/" component={aContainer}>
您所做的是创建一个“功能性未命名包装组件”,它不接受任何 Prop ,也不进一步向下传递任何 Prop 。
请注意,您不应使用 withRouter()
广泛地。这个 HOC 只是将路由器注入(inject)到不会由匹配路由本身渲染的组件中,例如组件树的更深处。在您的情况下,您不需要它。
关于javascript - Prop 中缺少位置(ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44866664/