反应路由器链接到,在地图功能内,只能工作一次

时间:2017-01-14 22:46:47

标签: javascript reactjs react-router

我已经关注了这个react router example,但是当我再次点击另一个用户时,似乎用户组件状态仍未改变。 所以,我只能看到一个用户。

的package.json

 {
  "name": "raspberry",
  "version": "1.0.0",
  "description": "raspberry =========",
  "main": "index.js",
  "scripts": {
    "start": "node webpack.dev-server.js",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^0.14.7",
    "react-bootstrap": "^0.30.7",
    "react-dom": "^0.14.7",
    "react-router": "^2.0.0",
    "superagent":"^3.3.2"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "bootstrap-sass": "^3.3.7",
    "css-loader": "^0.26.1",
    "extract-text-webpack-plugin": "^1.0.1",
    "file-loader": "^0.9.0",
    "node-sass": "^4.3.0",
    "react-bootstrap": "^0.30.7",
    "react-hot-loader": "^1.3.0",
    "sass-loader": "^4.1.1",
    "style-loader": "^0.13.1",
    "webpack": "^1.14.0",
    "webpack-dev-server": "^1.16.2"
  }
}

app.js

ReactDom.render((
    <Router history={hashHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={Home} />
            <Route path="/home" component={Home}/>
            <Route path="/users" component={Users}>
                <Route path="/users/:userId" component={User}/>
            </Route>
            <Route path="*" component={NoMatch} />    
        </Route>
    </Router>
), document.getElementById('app'));

Users.js

const Users = React.createClass({
    getUsers: function() {
        var self = this;
        request
            .get('/api/users')
            .set('Auth', 'Bearer '+ this.state.token)
            .end(function(err, res){
                if (res.statusCode === 200){
                    self.setState({
                        users:JSON.parse(res.text)
                    }) ;

                }else{
                    console.log('Get Users failed');
                }

        });

    },
    getInitialState: function(props) {
        props = props || this.props;
        return {
            token : localStorage.getItem("token"),
            users:[]

        };
    },
    componentDidMount: function() {
        this.getUsers();
    },
    render: function() {
        return(
            <div>
                <h1>Users</h1>
                <div className="master">
                  <div className="list-group">
                    {this.state.users.map(user => (
                      <Link to={`/users/${user.id}`} key={user.id} className="list-group-item">{user.username}</Link>
                    ))}
                  </div>
                </div>
                <div className="detail">
                  { this.props.children }
                </div>
              </div>
        );
    }
});

export default Users;

user.js的

const User = React.createClass({
    findUserById: function(id){
        var self = this;
        request
            .get('/api/users/'+id)
            .set('Auth', 'Bearer '+ localStorage.getItem("token"))
            .end(function(err, res){
              console.log(res);
                if (res.statusCode === 200){
                    self.setState({
                        user:JSON.parse(res.text)
                    }) ;

                }else{
                    console.log('Get User failed');
                }

        });
    },
    getInitialState: function() {
        return {user:''};
    },       
    componentDidMount: function() {
        console.log('componentDidMount');
        this.findUserById(this.props.params.userId)
    },

  render:function() {
    return (
      <div>
        <h2>{this.state.user.username}</h2>
      </div>
    )
  }
});
export default User;

1 个答案:

答案 0 :(得分:0)

如果您位于/users/17位置,则会呈现组件<Layout><Users><User>。然后,如果您导航到位置/users/5,您仍将呈现相同的组件。这意味着,为了<User>根据新的params进行呈现,您需要在该组件上实施componentWillReceivePropscomponentDidUpdate方法。