如何将页面状态传递给其他React?

时间:2018-04-29 15:59:53

标签: javascript reactjs

如果以其他方式使用,我想知道如何将状态从一个页面传递到另一个页面。

我的第一页Body.js(我处理状态):



import React from 'react';
import './Body.css';
import axios from 'axios';
import { Link } from "react-router-dom";
import User from './User';

class Body extends React.Component {
    constructor (){
        super();
        
        this.state ={
            employee:[],
            employeeCurrent:[],
        }
    }
    
    componentDidMount(){
        axios.get('http://127.0.0.1:3004/employee').then(
        response=>this.setState({employee: response.data})
    )
}

getName = () => {
    const {employee} = this.state;
    return employee.map(name=> <Link className='link' to={`/user/${name.name}`}> <div onClick={()=>this.add(name)} key={name.id} className='item'>  <img className='img' src={`https://picsum.photos/${name.name}`}></img> <h1 className='name'> {name.name} </h1></div> </Link>)
}

add = (name) => {
    const nam = name;
    this.state.employeeCurrent.push(nam)
    console.log(this.state.employeeCurrent)
}

render(){
    return(
        <div className='body'>
            {this.getName()}
        </div>
    )
}
}


export default Body;
&#13;
&#13;
&#13;

我想要获得名为employeeCurrent的状态的第二页:

&#13;
&#13;
import React from 'react';
import Header from './Header';
import Body from './Body';


class User extends React.Component {
    constructor (props){
        super(props);
        
        this.props ={
            employeeCurrent:[],
        }
    }

    render(){
        return(
        <div >
        {this.props.employeeCurrent}
        </div>
        )
    }
}

export default User;
&#13;
&#13;
&#13;

我使用React Router,它看起来像这样:

&#13;
&#13;
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './Home';
import User from './User';

const AppRouter = () => (
  <Router>
    <div className='router'>
      <Route exact path="/" component={Home}/>
      <Route path="/user/:id" component={User}/>
    </div>
  </Router>
);

export default AppRouter;
&#13;
&#13;
&#13;

我的项目是: 在主页上,您拥有从API获得的用户,所有用户都拥有属性(名称,年龄,城市和国家/地区)。保存在employeeCurrent变量中: enter image description here

我想要的是:从点击的用户那里获取这些属性并在用户页面上播放: enter image description here

有人可以帮我吗?????

1 个答案:

答案 0 :(得分:1)

就像我之前解释的那样,你需要解除状态:

AppRouter (保存状态并将其传递给儿童)

class AppRouter extends React.Component {
  state = {
    employeeCurrent: [],
    employee: []
  };

  componentDidMount() {
    axios
      .get("http://127.0.0.1:3004/employee")
      .then(response => this.setState({ employee: response.data }));
  }

  add = name => {
    this.setState(prevState => {
      const copy = prevState.employeeCurrent.slice();
      copy.push(name);
      return {
        employeeCurrent: copy
      };
    });
  };

  render() {
    return (
      <Router>
        <div className="router">
          <Route
            exact
            path="/"
            render={props => (
              <Home
                {...props}
                add={this.add}
                employee={this.state.employee}
                currentEmployee={this.state.currentEmployee}
              />
            )}
          />
          <Route
            path="/user/:id"
            component={props => (
              <User
                {...props}
                employee={this.state.employee}
                currentEmployee={this.state.currentEmployee}
              />
            )}
          />
        </div>
      </Router>
    );
  }
}

正文和用户(将父状态作为道具与更新程序功能一起接收):

class Body extends React.Component {
  getName = () => {
    const { employee, add } = this.props;
    return employee.map(name => (
      <Link className="link" to={`/user/${name.name}`}>
        {" "}
        <div onClick={() => add(name)} key={name.id} className="item">
          {" "}
          <img
            className="img"
            src={`https://picsum.photos/${name.name}`}
          />{" "}
          <h1 className="name"> {name.name} </h1>
        </div>{" "}
      </Link>
    ));
  };

  render() {
    return <div className="body">{this.getName()}</div>;
  }
}

class User extends React.Component {
  render() {
    // you will need to map employeeCurrent somehow
    return <div>{this.props.employeeCurrent}</div>;
  }
}