React app componentDidMount呈现两次

时间:2018-04-29 18:07:48

标签: reactjs fetch react-props react-lifecycle

我有一个简单的反应应用程序,它具有一个Login,在成功验证时接收Json Web Token并将其传递给兄弟组件(Members),在其componentDidMount中使用此JWT对服务器进行提取调用。问题是componentDidMount被调用两次,第一次使用未定义的JWT,第二次使用检索到的JWT。 继承我的代码:

App(父代码):

class App extends Component{
  state = {
    clientToken: ''
  }

  callbackGetToken = (token) => {
    this.setState({clientToken: token});
  }


  render(){
    return(
      <Switch>
        <Route exact path="/" component={props => <Login sendToken = {this.callbackGetToken}/>}/>
        <Route exact path="/members" component={props => <Members authToken = {this.state.clientToken}/>}/>
      </Switch>
    )
  }
};

export default App;

登录组件:

class Login extends Component {

  state = {
    credentials:{
      "username": "", 
      "password": ""
    },
    clientToken: ""
  }

  constructor(props){
    super(props);
    this.handleUsernameChange = this.handleUsernameChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
  }

  handleUsernameChange(event){
    this.state.credentials.username = event.target.value;
  }


  handlePasswordChange(event){
    this.state.credentials.password = event.target.value;
  }

  handleFormSubmit(event){
    event.preventDefault();
    const data = JSON.stringify(this.state.credentials);

    fetch(loginFormurl, {
      method: 'POST',
      headers: {
        "Content-Type": "application/json"
      },
      body: data,
    })
    .then((response) => {
      if(response.ok){
        const token = response.headers.get('Authorization');
        console.log(token);
        this.setState({clientToken: token});
        this.props.sendToken(token);
      }else{
        console.log(response.statusText);
      }
    })

    .catch(function(error) {
      console.log(error);
    });
  }

  render() {
    if (this.state.clientToken !== "") {
      return <Redirect to='./members' />;
    }

    return (
      <div className="App">
        <h1 className="Login-title">Login to Social Media Aggregator</h1>
        <form className="Login-box" onSubmit={this.handleFormSubmit}>
          <p>
            <label>
              Username
              <input id="username" type="text" name="username" required onChange={this.handleUsernameChange}/>
            </label>
          </p>
          <p>
            <label>
              Password
              <input id="password" type="password" name="password" autoComplete="password" required  onChange={this.handlePasswordChange}/>
            </label>
          </p>
          <p><input type="submit" value="Login"/></p>
        </form>
      </div>
    );
  }
}

export default withRouter(Login);

兄弟会员组成部分:

class Members extends Component{
    constructor(props){
        super(props);
        this.state = {
            interrests: [],
            authToken: props.authToken
        }
    }

    componentDidMount(){
        fetch(interestUrl, {
            method: 'GET',
            headers: {
              "Content-Type": "application/json",
              "Authorization": this.state.authToken
            }
          })
          .then((response) => {
            if(response.ok){
              console.log(response.json());
            }else{
              console.log(response.statusText);
            }
          })
    };

    render(){
        return(
            <div>
                <Menu/>
                <Main/>
            </div>
        )
    }

}
export default Members;

关于如何解决这个问题的任何想法?谢谢!

更新

发现问题。似乎登录中的重定向组件正在创建两次成员组件。如果我从页面中删除重定向,而只是放置一个链接来进行重定向,它只会呈现一次。不过,不知道如何解决这个问题:(

0 个答案:

没有答案