기본 설치 방법.
npm install zustand
import create from 'zustand'
파일저장소 생성
//파일저장소 //디버깅툴 감싸기
const useStore = create (devtools((set)=>({
count: 0,
증가(){ //사용해야할것
set((state)=>({ count : state.count +1 }))
},
//ajax 요청법
async ajax요청(){
const response = await fetch('https://codingapple1.github.io/data.json');
console.log(await response.json());
}
})))
가져오기
const Card = () => {
const {count} = useStore();
return (
<div>
<p>카드 {count}</p>
</div>
);
};
export default App;
아무 컴포넌트에서나 사용가능
저장소안에 두번째 저장소 만드는법.
//파일저장소2 //디버깅툴 감싸기
const useStore2 = create (devtools((set)=>({
count2: 0,
감소(){ //사용해야할것
set((state)=>({ count2 : state.count2 -1 }))
},
})))
두번째 저상소 사용법
const App = () => {
const {count, 증가,ajax요청} = useStore(); //가져올때 컴포넌트에 써야할훅
const {감소, count2} = useStore2(); //가져올때 컴포넌트에 써야할훅
return (
<div>
<p>구독자 {count} {count2}</p>
<button onClick={()=>{
증가();
ajax요청(); //불러오는 방법 쉽다.
}}>+</button>
<button onClick={()=>{
감소();
ajax요청(); //불러오는 방법 쉽다.
}}>-</button>
<Card/>
</div>
);
};
디버깅툴 사용법
import {devtools, persist} from "zustand/middleware";
임포트 후에 create 를 devtools로 감싸주기
const useStore = create (devtools((set)=>({ 코드들 }) )
전체코드
import React from 'react';
import create from 'zustand'
//디버깅 방법 //미들웨어 state 변경하기전에 특정코드 실행하고싶을때
import {devtools, persist} from "zustand/middleware";
//파일저장소 //디버깅툴 감싸기
const useStore = create (devtools((set)=>({
count: 0,
증가(){ //사용해야할것
set((state)=>({ count : state.count +1 }))
},
//ajax 요청법
async ajax요청(){
const response = await fetch('https://codingapple1.github.io/data.json');
console.log(await response.json());
}
})))
//파일저장소2 //디버깅툴 감싸기
const useStore2 = create (devtools((set)=>({
count2: 0,
감소(){ //사용해야할것
set((state)=>({ count2 : state.count2 -1 }))
},
})))
const App = () => {
const {count, 증가,ajax요청} = useStore(); //가져올때 컴포넌트에 써야할훅
const {감소, count2} = useStore2(); //가져올때 컴포넌트에 써야할훅
return (
<div>
<p>구독자 {count} {count2}</p>
<button onClick={()=>{
증가();
ajax요청(); //불러오는 방법 쉽다.
}}>+</button>
<button onClick={()=>{
감소();
ajax요청(); //불러오는 방법 쉽다.
}}>-</button>
<Card/>
</div>
);
};
const Card = () => {
const {count} = useStore();
return (
<div>
<p>카드 {count}</p>
</div>
);
};
export default App;