状态已更改但组件未重新呈现

时间:2017-07-20 08:54:36

标签: reactjs react-native

我是新手做出反应原生的,我现在用它来构建应用程序。我今天发现了两个问题,如果有人能帮我理解这些问题,那将会非常有帮助和欣赏。

在此应用中,我使用react native + Expo + redux + react-native-elements(组件库)+ react-native-debugger(debug react-native和redux )。

第一个问题(已解决!):

在我的Auth.js中,我想渲染一个按钮,按钮的字符串取决于州的一个切片。

class Auth extends Component{
  constructor(props){
    super(props);
  }

  // Why this not work???
  // renderBtn(){
  //   btnString = this.props.isLoginPage?"Log In":"Sign Up";
  //   return(
  //     <Button
  //         title={btnString}
  //         big
  //         backgroundColor="#64B5F6"
  //         onPress={this.props.onAuth}
  //       />
  //   )
  // }

  //this works well
  renderBtn(){
    if (this.props.isLoginPage) {
      return(
        <Button
          title="Log In"
          big
          backgroundColor="#64B5F6"
          onPress={this.props.onAuth}
        />
      );
    }

      return(
        <Button
          title="Sign Up"
          big
          backgroundColor="#64B5F6"
          onPress={this.props.onAuth}
        />
      );
  }

...

  render(){
    return(
      <View>
      ...

        {this.renderBtn()}

      ...

      </View>

    )
  }
}
//map isLoginPage from state to props
const mapStateToProps = ({auth}) => {
  const {emailErrorMsg,passwordErrorMsg,email,password,isLoginPage,isLoading} = auth;
  return {emailErrorMsg,passwordErrorMsg,email,password,isLoginPage,isLoading};
}

export default connect(mapStateToProps,{
  onPasswordChanged,
  onEmailChanged,
  onAuth,
  onSwitchAuthType
})(Auth);

如上所述,我想使用this.props.isLoginPage来确定显示哪个字符串。 &#34; isLoginPage&#34;是一段状态,使用react-redux映射到组件的道具。

当我单击一个按钮以反转isLoginPage,并且调试器显示它已更改,但我评论的函数renderBtn()不起作用时,它只是没有响应,低于renderBtn()效果不错。

Button component来自react-native-elements

我想知道它为什么会发生,如果有任何文件会很有帮助。

Sencond问题:

AuthReducer.js中(由上面的Auth.js使用)。我想反转isLoginPage

import {PASSWORD_CHANGE,EMAIL_CHANGE,SWITCH_AUTH_TYPE,AUTH_START} from '../Type';

const INIT_STATE = {
  isLoginPage:false,

  isLoading:false,
  email:'',
  password:'',
  emailErrorMsg:'',
  passwordErrorMsg:'',
};


export default (state = INIT_STATE, action)=>{
  switch(action.type){
    case EMAIL_CHANGE:
      return {...state, email:action.payload};
    case PASSWORD_CHANGE:
      return {...state, password:action.payload};

    case SWITCH_AUTH_TYPE:
      //Why this not work???
      //return {...state, isLoginPage:!state.isLoginPage}
      const newIsLogin = !state.isLoginPage;
      return {...state,isLoginPage:newIsLogin};

    case AUTH_START:
      return {...state,isLoading:true};
    default:
      return state;
  }
}

我评论了不工作的代码(isLoginPage值没有改变,react-native-debugger),下面的代码运行良好。 似乎完全相同。我无法理解,我对ES6感到遗憾?

1 个答案:

答案 0 :(得分:1)

你刚刚错过了声明变量,它应该是

let btnString = this.props.isLoginPage?"Log In":"Sign Up";

使用ESLint应该是:

let btnString = this.props.isLoginPage ? 'Log In' : 'Sign Up';
相关问题