演習④ React Nativeで、カウンターを作成する際に、zustandを使う。

まず、普通に作成すると下記のようになる。

Stateをどのコンポーネントに作成するかは重要である。

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import {useState} from 'react';

function SubCounter(props){
  const increaseCount = () =>{
    props.inc();
  }
  return(
    <View>
      <Text>{props.title}</Text>
      <Text>{props.count}</Text>
      <Button title='+'
              onPress={increaseCount}
      />
    </View>
  )
}

export default function App(){
  const [count, setCount] = useState(0);
  const [count2, setCount2] = useState(0);
  const increaseCount = () =>{
    setCount*1
}));

export default useStore;

 

 

*1:count) => count + 1);

  }
  const increaseCount2 = () =>{
    setCount2((count2) => count2 + 1);
  }

  const totalCount = count + count2;

  return(
    <View>
      <Text style={{fontSize:20}}>Counter</Text>
      <SubCounter inc={increaseCount}
                  title='軽自動車'
                  count={count}
      />
      <SubCounter inc={increaseCount2}
                  title='乗用車'
                  count={count2}
      />
      <Text style={{marginTop: 50, fontSize: 30}}>総台数:{totalCount}</Text>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    backgroundColor: '#fff',
    alignItems:'center',
    justifyContent: 'center'
  }
});


 

さて、それではzustandを使って書き直します。

 

App.js と同列で store.jsを作成します。

(プロジェクト)/store.js

import {create} from 'zustand';

const useStore = create((set) => ({
    id:0,
    setId:(value) => set((state) => ({ id:value }