【问题标题】:React props is undefinedReact 道具未定义
【发布时间】:2016-11-08 15:37:05
【问题描述】:

我正在尝试通过 react-router 将道具从一个组件传递到另一个组件。当我尝试从子组件获取该道具时,我收到了此消息 TypeError: this.props.params.appState is undefined 。这是我的代码:

Tracks.jsx:

import { observable } from 'mobx';


export default class Tracks {
    @observable tracks = [];

}

app.jsx:

.......
import Tracks from './store/Tracks.jsx';

......
const appState = new Tracks();

ReactDOM.render(
    <Router history={browserHistory} >
        <Route path="/" component={Login} />
        <Route path="/dashboard" onEnter={authRequired} component={Main}>
            <Route path="album/create" component={AlbumCreate} />
            <Route path="album/:id" component={Album} appState={appState}/>
            <Route path="album/:id/upload"  component={Upload} />
        </Route>
    </Router>,
    document.getElementById('app')
);

专辑.jsx:

.....
@observer
export default class Album extends React.Component {

    constructor(props) {
        super(props);
    }
componentDidMount () {
        console.log(this.props.params.appState.tracks);
    }

.....

【问题讨论】:

  • 你能检查一下this.props的内容吗?
  • 我可以看到错误提示 TypeError: this.props.params.appState is undefined 所以看来 appStateundefined 而不是 this.props 本身。
  • @MarioAlexandroSantini Object { history: Object, location: Object, params: Object, route: Object, routeParams: Object, routes: Array[2], children: null, 2 more… }
  • @Kamil 我只是想看看poperty是否直接在this.props中。
  • Here 有一个关于如何做到这一点的例子。如果有问题请检查并回来。

标签: javascript reactjs react-router


【解决方案1】:

改变这个

this.props.params.appState

this.props.route.appState

Params 是 URL 的动态段,对于 props 你需要路由

【讨论】:

    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2022-06-30
    • 2018-11-05
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多