2017-07-22 49 views
0

在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); 

回答

3

你看不到它,因爲你的組件沒有簽約店。任何與商店有關的事情都是Redux的工作,並且不是 React Native。所以如果你將你的組件封裝在react-redux裏,並且將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); 

爲了使它正常工作,請確保您設置的終極版店內正常。將您的根組件包裝在提供程序組件中並傳入存儲中。假設你的根組件被稱爲應用程序,那麼它看起來像下面這樣:

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> 
    ) 
    } 
} 
+0

這是一個非常豐富的答案。感謝您的幫助。我仍然收到錯誤消息:無法在「連接(主)」的上下文或道具中找到「商店」。將根組件包裝在中,或將「存儲」明確傳遞給Connect(主)。我嘗試了錯誤中的第一個建議的解決方案,但沒有任何幫助。我不明白第二個。有任何想法嗎? – Bob

+0

第一種方法應該工作。代碼中可能存在錯誤。我已經更新了我的答案,以包含關於如何在您的組件上設置redux商店的示例。此外,還原文檔是一個很好的來源:http://redux.js.org/docs/basics/UsageWithReact.html#passing-the-store –

相關問題