在React中从父级到子级的回调函数

时间:2019-12-10 16:37:53

标签: node.js reactjs express

我有一个父级App和一个子级Login。在Login组件中,用户可以正确登录,我可以将用户详细信息存储在setState中。但是我想通过名为App的函数从父级通过回调函数将此状态传递给父级userState

这里是父级App

const { BrowserRouter, Link, Switch, Route, browserHistory } = ReactRouterDOM;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentUser: ""
    }
  }
  userState = (user) => {
    this.setState = {
      currentUser: user
    }
  }
  render() {
    return (
      <BrowserRouter>
        <div>
          <Nav />
          <Switch>
            <Route exact path="/someroute1">
              <Someroute1 />
            </Route>
            <Route path="/login">
              <Login userState={this.userState} currentUser={this.state.currentUser} />
            </Route>
            <Route path="/route2">
              <Someroute2 />
            </Route>
          </Switch>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

ReactDOM.render(<App />, document.querySelector(".container"));

这里是孩子Login

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: "",
            password: "",
            currentUser: this.props.currentUser
        }
    }
    handleChange = event => {
        this.setState({ [event.target.id]: event.target.value })
    }
    handleSubmit = event => {
        event.preventDefault();
        fetch("/sessions", {
            body: JSON.stringify(this.state),
            method: "POST",
            headers: {
                Accept: "application/json, text/plain, */*",
                "Content-Type": "application/json"
            }
        })
            .then(loggedInUser => {
                return loggedInUser.json();
            }).then(jsonedUser => {
                this.props.userState(jsonedUser); // <- this doesn't seem to work
                console.log('Current User is:', this.state.currentUser) // <- this.state.currentUser is blank
            })
            .catch(error => console.log(error));
    };

    render() {
        return (
            <React.Fragment>
                <h1>Login</h1>
                <form onSubmit={this.handleSubmit}>
                    <label htmlFor="username">Username</label>
                    <input type="text" id="username" name="username" value={this.state.username} onChange={this.handleChange} />
                    <label htmlFor="password">Password</label>
                    <input type="password" id="password" name="password" value={this.state.password} onChange={this.handleChange} />
                    <input type="submit" value="Submit" />
                </form>
            </React.Fragment>
        );
    }
}

我已经阅读了本教程https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17,并从stackoverflow中获取了很多答案,但是不知何故,我的回调函数无法执行任何操作。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

这是您收到的错误。

首先,Parent JS看起来很棒!

childJS中存在一些问题,它们从这里开始:

    this.state = {
    ...  
    currentUser: this.props.currentUser
}

大概是它们跟踪到组件的其余部分(即您要在其中显示用户看到的内容)。

您需要做的是保持数据流的一致性。 ChildJS不需要状态,只需要显示父状态(由props传递下来)。

ParentJS(状态:用户,setState)=>

然后,子JS将是:render(){return({currentUser})}

答案 1 :(得分:0)

这可能会帮助您

父母

import Child from '../child.js';

class Parent extends Component {

 getValue = (data) =>{
  //Login data
  console.log(data);
 }

 render(){
  return(
   <div>
    <Child getValue={this.getValue} />
   </div>
  )
 }
}

孩子

 class Child extends Component {

 onLogin = () =>{
  this.props.getValue('any data to parent here');
 }

 render(){
  return(
   <div>
    <button onClick={()=>this.onLogin}>Login</button>
   </div>
  )
 }
}