【问题标题】:React component is not re-rendering on state changeReact 组件不会在状态更改时重新渲染
【发布时间】:2018-03-17 19:26:24
【问题描述】:

所以我在更新组件的状态时遇到了问题。 this.state.authenticated 被传递给 Navigation 以隐藏/显示登录/注销按钮。但是,一旦用户登录,状态更改就不会重新呈现导航。我必须手动刷新页面才能看到导航栏重新呈现并显示注销按钮。

这里是代码

const token = window.localStorage.getItem("token");

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      authenticated: false,
    }
  }
  componentWillMount() {
    console.log('app token:', token);
    if (token) {
      this.setState({ authenticated: true});
    } else {
      this.setState({authenticated: false});
    }
    console.log('app componet will mount:', this.state.authenticated);
  }
  render() {
    return (
      <div className="App">
        <Navigation authenticated={this.state.authenticated}/>
        <Route path='/' exact component={Register} />
        <Route path='/feed' exact component={Feed} />
        <Route path='/login' component={Login} />
        <Route path='/feed/:id'  component={SingleGroup} />
        <Route path='/mygroups'  component={MyGroups} />
      </div>
    );
  }
}

登录操作代码

export const login = (username, password, history) => {
  axios.defaults.withCredentials = true;
  return (dispatch) => {
    axios.post(`${url}/user/login`, {username, password})
      .then((data) => {
        dispatch({
          type: 'SIGNIN_USER',
          payload: data,
        })
        window.localStorage.setItem('token', data.data.token);
        history.push('/feed');
      })
      .catch((err) => {
        dispatch({
          type: 'SIGNIN_ERROR',
          payload: err,
        });
      });
  };
};

【问题讨论】:

  • 令牌从何而来?
  • 我从本地存储中获取它。如果用户认证成功则设置
  • 它的代码在哪里?
  • 添加到问题
  • 好的,很好。现在你从哪里得到令牌?获取token的代码在哪里?

标签: reactjs


【解决方案1】:

State authenticated 仅在 componentWillMount 时设置一次。您的 App 组件未连接到 redux 商店,因此当商店数据更改时,App 不会重新呈现。并且此时 state.authenticated 直到 false
所有数据都应该来自 redux 存储(不是组件状态)。
解决方法:
- 将 App 连接到 redux 商店或将 Navigation 连接到 redux 商店。
- 在ma​​pStateToProps函数中,获取“authenticated”值并返回给组件props;
- 根据 this.props.authenticated 值呈现导航。

Redux Connect Tutorial

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2020-03-03
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多