在Redux存储更新其值后,为什么我的组件的状态计算属性更新?

时间:2017-07-22 04:14:52

标签: react-native redux

为什么在Redux存储更新其值后,我的组件的状态计算属性更新是不是?

我正在使用一些辅助方法通过AppStore.getState()获取子存储.ApiStore用于我的isAuthenticated状态属性。看起来当这个商店值更新时,组件状态值不会更新。 React Native不会在计算组件状态属性中监视商店更新吗?

我的组件如下所示:

// Vendor
import React, { Component } from 'react'
import { AppRegistry, Text, View, StyleSheet, TextInput, Button} from 'react-native'
import AppStore from './Stores/AppStore'
import StoreHelpers from './Stores/StoreHelpers'

// Custom
import Login from './Components/Login/Login'
import Api from './Services/Api.js'

// Styles
const styles = StyleSheet.create({

  mainView: {
    flex: 1,
    padding: 20,
    marginTop: 30,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3b5998',
  },

});

// Main App Component
export default class Main extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      isAuthenticated: !StoreHelpers.getApiStore().userBalanceResponse.error // Computed property from store
    }

    // Enable this for debugging

    console.log(this.state)

    AppStore.subscribe(() => {
     console.log(AppStore.getState())
    })

  }

  render() {
    return (
      <View style={styles.mainView}>
        <Login />
      </View>
    )
  }
}

// skip this line if using Create React Native App
// AppRegistry.registerComponent('AwesomeProject', () => Main);

1 个答案:

答案 0 :(得分:1)

您无法看到它,因为您的组件未订阅商店。与商店有关的任务是redux和 NOT React Native的工作。因此,如果将组件包装在react-redux connect中并将mapStateToProps传递给它,则应获得正确的计算值。

// ... rest of imports
import { connect } from 'react-redux';

// Main App Component
class Main extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      isAuthenticated: this.props.isAuthenticated,
    }

    // ... rest of code

  }

  // ... rest of code
}

const mapStateToProps = (store) => ({
  isAuthenticated: !userBalanceResponse: store.userBalanceResponse.error,
});

export default connect(mapStateToProps, null)(Main);

要使其正常工作,请确保正确设置redux存储。将根组件包装在Provider组件中并将存储器传入其中。假设您的根组件名为App,那么它看起来如下所示:

import { Provider } from 'react-redux';
import { createStore } from 'redux';
import Main from 'path-to-main/Main';

// we will pass this store to the Provider
const store = createStore(
  reducer,
  // ... middlewares etc this is optional
);

export default class App extends Component {
  render() {
    return(
      <Provider store={store}>
        <Main />
      </Provider>
    )
  }
}