상태관리 라이브러리 Zustand
// store.js
import create from 'zustand'
const useStore = create(set => ({
deviceId: "", // 변수
setDeviceId: (id) => set(() => ({deviceId: id})), // 함수
deviceName: "deviceNameExample",
setDeviceName: (name) => set(() => ({deviceName: name})),
init: false,
bluetoothState: false,
scanning: false,
found: false,
connecting: false,
connected: false
...
}))
export default useStore
1. 클래스형 컴포넌트
// Example.js
...
// 불러와서
import useStore from '../store/store';
export default class Example {
constructor() {}
initState() {
// 사용
// useStore.getState().deviceName
// useStore.getState().setDeviceName("Change")
console.log("deviceName"+useStore.getState().deviceName);
useStore.getState().setDeviceName("Change"); // 함수 실행
console.log("deviceName"+useStore.getState().deviceName); // 변수 출력
}
...
2. 함수형 컴포넌트
...
import useStore from '../store/store';
const App = () => {
// 불러와서
const {
deviceId, deviceName, deviceArr, deviceList,
init, bluetoothState, scanning, found, connecting, connected,
notifyServiceUUID, notifyCharacteristicUUID,
writeServiceUUID, writeCharacteristicUUID
} = useStore(state => state);
...
// ex : {deviceId} {deviceName} 이런식으로 사용
return(
<SafeAreaView style={styles.container}>
<View style={connectStyles.container}>
{connecting ?
<View style={connectStyles.wrap}>
<Text style={[connectStyles.drawState, connectStyles.connect]}></Text>
<Text>연결됨</Text>
</View>:<View style={connectStyles.wrap}>
<Text style={[connectStyles.drawState, connectStyles.disconnect]}></Text>
<Text>연결안됨</Text>
</View>
}
</View>
...
);
}