状態管理のやり方
React Context
ライブラリ不要。
const AppContext = React.createContext(null); // Consumer配下のcontextでアクセス function LoginScreen() { return ( <AppContext.Consumer> {(context) => ( <Text>LoginScreen</Text> <Button title="login" onPress={() => context.setLogin(true)}></Button> </View> )} </AppContext.Consumer> ); } // ルートはProviderで囲う(管理する値はvalueに定義) <AppContext.Provider value={this.state}> </AppContext.Provider> // Componentをラップする関数 export const Connect = (ChildComponent) => (props) => ( <AppContext.Consumer> {(context) => <ChildComponent {...props} context={context} />} </AppContext.Consumer> );
unstated
GitHub - jamiebuilds/unstated: State so simple, it goes without saying
React Contextとあまり変わらない感じもするけど。
import { Provider, Subscribe, Container } from 'unstated'; // 管理する値を定義 class Store extends Container { state = { isLogin: false, }; setLogin = async (isLogin) => { this.setState({ isLogin }); }; } // Subscribe配下のcontextでアクセス。Storeもわたす。 function LoginScreen() { return ( <Subscribe to={[Store]}> {(context) => ( <View style={styles.container}> <Text>LoginScreen</Text> <Button title="login" onPress={() => context.setLogin(true)}></Button> </View> )} </Subscribe> ); } // Componentをラップする関数 const Connect = (ChildComponent) => (props) => ( <Subscribe to={[Store]}> {(context) => <ChildComponent {...props} context={context} />} </Subscribe> ); // ルートはProviderで囲う <Povider> <Subscribe to={[Store]}> <Povider>
unstatet-next
React Hookを使った書き方になります。Functional Componentの場合はこちらが良いのか。こちらのほうが新しいようなので主流になるのだろうか。
render以外でも使えそうなので、HighOrderComponentにするための関数はいらない感じがする。
なんだかいい感じ。
import { createContainer } from 'unstated-next'; // 管理する値を定義 function useStore(initialState = 0) { let [isLogin, setLogin] = React.useState(false); let login = () => setLogin(true); let logout = () => setLogin(false); return { isLogin, setLogin, login, logout }; } const StateContainer = createContainer(useStore); // useContainerでアクセス function LoginScreen() { let container = StateContainer.useContainer(); return ( <View style={styles.container}> <Text>LoginScreen</Text> <Button title="login" onPress={() => container.setLogin(true)}></Button> </View> ); } // ルートはProviderで囲う <StateContainer.Provider> </StateContainer.Provider>
redux
諦めて最初からこれを使うのがいいような気もしてきた。