Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 属性在React组件中显示为未定义-检索props.match和组件中的其他属性_Reactjs_React Router - Fatal编程技术网

Reactjs 属性在React组件中显示为未定义-检索props.match和组件中的其他属性

Reactjs 属性在React组件中显示为未定义-检索props.match和组件中的其他属性,reactjs,react-router,Reactjs,React Router,我有一个index.js,我从中调用一个类似这样的组件 const prop1 = 'test' ReactDOM.render( <BrowserRouter> <Switch> <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/> </Switch> </BrowserRouter>, docu

我有一个index.js,我从中调用一个类似这样的组件

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" component={MyComponent} prop1={prop1}/>
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
const prop1='test'
ReactDOM.render(
,
document.getElementById('root'))
);
但是在MyComponent.js中,
this.props.prop1
显示为未定义。知道为什么吗?
我需要能够获得this.props.match.params和prop1

@jornsharpe的评论非常重要:

路线仅将路线道具、历史记录、比赛和位置传递给 它安装的组件

因此,如果要将道具传递给管线中的组件,应如下所示:

<Switch>
   <Route path="/pathname" render={() => (<MyComponent prop1={prop1}/>)} />
</Switch>

()} />

如果需要将道具传递给React Router正在渲染的组件,而不是使用Routes组件道具,请使用其渲染道具传递内联函数,然后将参数传递给正在创建的元素

<Route
  path='/pathname'
  render={(prop1) => <MyComponent props={prop1} />}
/>
}
/>
请试试这个,应该可以用。

const prop1='test'
const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/" component={() => <MyComponent prop1={prop1}>} />
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);    
ReactDOM.render( } /> , document.getElementById('root')) );
这将把匹配、位置、历史记录和自定义道具传递给新组件

const prop1 = 'test'
ReactDOM.render(

<BrowserRouter>
    <Switch>
        <Route path="/pathname/:param1/:param2" render={(props) => <MyComponent {...props} prop1={prop1} />} />
    </Switch>
</BrowserRouter>,
document.getElementById('root')
);
const prop1='test'
ReactDOM.render(
} />
,
document.getElementById('root'))
);

Route
只将路由道具、
历史记录
匹配
位置
传递给它装载的组件。这种方法的问题是,道具、历史记录、匹配和位置不会传递给组件,只传递了道具1。这里的问题是,我得到了道具1,但没有得到道具。match(因为我有路径参数,我需要在Mycomponent中获取这些参数)。