React this.props.params undefined React this.props.params未定义
React this.props.params undefined React this.props.params未定义
我在传递id
到产品页面的过程中遇到了问题,我尝试了一切并搜索答案,但仍然无法解决。
这是我的index.js文件:
import React from "react"; import {render} from "react-dom"; import {Router, Route, IndexRoute, hashHistory} from "react-router"; import {Menu} from './components/Menu'; import {MainPage} from './components/MainPage'; import {DetailsProduct} from './components/DetailsProduct'; class App extends React.Component{ render(){ return({/* ) } } render(*/} ( )}> ( asd )}>, window.document.getElementById("app"));
以及DetailsProduct文件
(页面链接:http://localhost:8080/#/product/1)
import React from "react"; export class DetailsProduct extends React.Component{ render(){ console.log(this.props.params); <-- 这是undefined return(Product
) } }
我在三年后回到这里。解决方法:
以这种方式渲染组件不是一个好的解决方案:
( asd )}>
但是如果您想以这种方式渲染组件(我不建议这样做),您必须将props作为参数传递给函数,并在您希望使用该props的组件中进行解构({...props})。
( asd )}>
最好的解决方案是以这种方式渲染路由:
并在DetailsProduct
中可以渲染或使用
Switch
:
// 在这里添加其他任何路由