react render方法被称为Twice,更改url

时间:2016-09-10 06:14:50

标签: reactjs react-router

我是新手的反应。我看了http://ilspy.net/,但没有解决我的问题。我认为我对componentWillReceiveProps理解错了。我的组件和它的父母是这样的: 父母:

import React from 'react';
import { Router, Route, Link } from 'react-router';

export default class App extends React.Component {

items = [
    {id: 1086, title: 'MENU1'},
    {id: 1083, title: 'MENU2'},
    {id: 1093, title: 'MENU3'}]

renderItems = ()=> {
    return this.items.map((item, index)=> {
        let url = 'content/' + item.id;
        return (<li key={index}><Link to={url} activeClassName="active">{item.title}</Link></li>);
    });
}


render() {
    return (
        <div>
            <h1 style={{textAlign:'center'}}>My First React App</h1>
            <ul className="nav nav-pills nav-justified">{this.renderItems()}</ul>
            {this.props.children}
        </div>
    );
}

}

小孩:

import React, { Component } from 'react';
import UmContent from './UmContent'
import $ from 'jquery';
import ProgressBar from 'progressbar.js';


export default class UmContentContainer extends Component {
state = {
    data: ''
}

firstInitial = true;

componentDidMount() {
    if (this.firstInitial) {
        let props = this.props;
        this.sendRequestToServer(props);
        this.firstInitial = false;
    }
}

sendRequestToServer = (props)=> {
    if (!props || !props.params || !props.params.id) {
        return;
    }
    let itemId = props.params.id;
    let that = this;
    this.setState({data: itemId});
     }

componentWillReceiveProps(props, states) {
    this.sendRequestToServer(props);
     console.log(props.params.id);
}

render() {
    return (
        <div className="col-md-12">
            <h1>{this.state.data}</h1>
        </div>);
}

}

和index.js:

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Link,hashHistory } from 'react-router'
import App from './App';
import UmContentContainer from './Umbreco/UmContentContainer';

render((
<Router history={hashHistory}>
    <Route path="/" component={App}>
            <Route path="/content/:id" component={UmContentContainer} />
    </Route>
</Router>
), document.getElementById('root'))

首次安装后,控制台写入&#34; id&#34;两次。我无法理解为什么?

1 个答案:

答案 0 :(得分:1)

我找到了答案HERE,我错了,实际上是关于hashHistory并推送新网址。不是componentWillReceiveProps