将路由参数传递给reactjs

时间:2016-12-06 20:49:59

标签: reactjs express

我正在使用react-router的路由,如下所示

<Route path="product/:id" component={Product}/>

我有以下代码的组件产品,如下所示

import React, {PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import { asyncConnect } from 'redux-async-connect';
import {load, isLoaded} from 'redux/modules/viewlodging';

@asyncConnect([{
    promise: ({ store: { dispatch, getState } }) => {
       const promises = [];
       if (!isLoaded(getState())) {
           promises.push(dispatch(load()));
       }
       return Promise.all(promises);
    }
}])

@connect(
    state => ({viewdata: state.viewlodging.data}),
    dispatch => bindActionCreators({load}, dispatch)
)

export default class Product extends React.Component {

    static propTypes = {
        viewdata: PropTypes.object,
        location: PropTypes.object,
        load: PropTypes.func.isRequired
    }

    render() {
        console.log(this.props.routeParams.id); // here I get routeparameter
        const { viewdata } = this.props;
        return (
            <div>
                <div>Sample test</div>
                </div>
                <Footer/>
                <Viewfootertext viewdata={viewdata}/>
            </div>
        );
    }
}

我想将参数id传递给reducer方法加载,如何以正确的方式传递路由参数?

2 个答案:

答案 0 :(得分:0)

您可以var root = 'https://jsonplaceholder.typicode.com'; var index = 0; $.ajax({ url: root + '/posts/1/comments', method: 'GET' }).then(function(data) { $("#button").click(function() { var notificationMessage = "Oops, there are no more user cards to display"; if (index >= data.length ) { return alert(notificationMessage); } $("#content").append('<div id="card"><div class="title"><div class="image"></div><div id="name">' + data[index].name + '</div><span id="close"></span></div><div id="description">' + data[index].body + '<a href="mailto:" id="email">' + data[index].email + '</a></div></div>' ); index++; // remove all cards from a list and return index equally [0], to be able add user card again. $("#clear").click(function() { $("#card").remove(); index = 0; }); }); }); //How to remove card by clicking on the close button? componentWillMount()发送。不要用componentDidMount()方法发送它,因为每当你有新的道具或状态变化时它就会触发。

您可以从render访问route params

请在this.props.params

中尝试这样做
container

你的容器看起来像这样

  componentDidMount(){
    const {id} = this.props.params;
    this.props.load(id); //you can send params values after component get mounted.
  }

答案 1 :(得分:0)

@asyncConnect([{
    promise: ({ store: { dispatch, getState }, params: { id }, }) => {
    const promises = [];
    if (!isLoaded(getState())) {
    promises.push(dispatch(load(id)));
    }
    return Promise.all(promises);
}
}])

传递带有params的id为我工作