React-redux组件不会在存储状态更改时重新呈现

Zal*_*oza 14 reactjs react-native redux react-redux

我今天说要学习反应和减少,但我无法弄清楚如何在状态改变后迫使组件重新渲染.

这是我的代码:

const store = createStore(loginReducer);
export function logout() { return {type: 'USER_LOGIN'} }
export function logout() { return {type: 'USER_LOGOUT'} }
export function loginReducer(state={isLogged:false}, action) {
  switch(action.type) {
    case 'USER_LOGIN':
      return {isLogged:true};
    case 'USER_LOGOUT':
      return {isLogged:false};
    default:


         return state;
      }
    }

    class App extends Component {

      lout(){
        console.log(store.getState()); //IT SHOW INITIAL STATE
        store.dispatch(login());
        console.log(store.getState()); //IT SHOWS THAT STATE DID CHANGE
      }

      ////THIS IS THE PROBLEM, 
    render(){
    console.log('rendering')
    if(store.getState().isLogged){
      return (<MainComponent store={store} />);
    }else{
      return (
        <View style={style.container}>
          <Text onPress={this.lout}>
          THE FOLLOWING NEVER UPDATE :( !!{store.getState().isLogged?'True':'False'}</Text>
          </View>
        );
    }    
}
Run Code Online (Sandbox Code Playgroud)

我可以触发更新的唯一方法是使用

store.subscribe(()=>{this.setState({reload:false})});
Run Code Online (Sandbox Code Playgroud)

在构造函数内部,以便我手动触发组件的更新状态以强制重新呈现.

但我如何链接商店和组件状态?

Dan*_*nny 19

只有在更改状态或道具时,您的组件才会重新渲染.您不是依赖于this.state或this.props,而是直接在渲染函数中获取商店的状态.

相反,您应该使用connect将应用程序状态映射到组件道具.组件示例:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';

export class App extends React.Component {
    constructor(props, context) {
        super(props, context);
    }

    render() {
        return (
            <div>
            {this.props.isLoggedIn ? 'Logged In' : 'Not Logged In'}
            </div>
        );
    }
}

App.propTypes = {
    isLoggedIn: PropTypes.bool.isRequired
};

function mapStateToProps(state, ownProps) {
    return {
        isLoggedIn: state.isLoggedIn
    };
}

export default connect(mapStateToProps)(App);
Run Code Online (Sandbox Code Playgroud)

在这个非常简单的示例中,如果商店的isLoggedIn值发生变化,它将自动更新组件上的相应prop,这将导致它呈现.

我建议您阅读react-redux文档以帮助您入门:http: //redux.js.org/docs/basics/UsageWithReact.html

  • `App.propTypes`是否需要使用`connect()`?看起来你只是扔在那里. (4认同)

duh*_*ime 5

我最终来到这里是因为我写了一个糟糕的减速器。我有:

const reducer = (state=initialState, action) => {
  switch (action.type) {
    case 'SET_Q':
      return Object.assign(state, {                     // <- NB no {}!
        q: action.data,
      })

    default:
      return state;
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要:

const reducer = (state=initialState, action) => {
  switch (action.type) {
    case 'SET_Q':
      return Object.assign({}, state, {                 // <- NB the {}!
        q: action.data,
      })

    default:
      return state;
  }
}
Run Code Online (Sandbox Code Playgroud)