6 글 보임 - 1 에서 6 까지 (총 6 중에서)
-
글쓴이글
-
2023년 9월 2일 00:48 #96613
신혜원참가자(shop.js) import { changeItem } from "../../store"; import { useDispatch } from "react-redux";
const [shopItems, setShopItems] = useState(); let dispatch = useDispatch();
useEffect(() => { axios .get( "https://raw.githubusercontent.com/mimkong/meongmeongdata/master/data.json" ) .then((result) => { setShopItems(result.data); dispatch(changeItem(result.data)); }) .catch(() => { console.log("json 데이터를 불러오는데 실패했습니다."); }); }, []); (store.js) import { configureStore, createSlice } from "@reduxjs/toolkit";
const item = createSlice({ name: "item", initialState: "", reducers: { changeItem(state) { return state; }, }, }); export default configureStore({ reducer: { item: item.reducer }, });
export const { changeItem } = item.actions;
(Detail.js) import { useSelector } from "react-redux";
function Detail() { let a = useSelector((state) => { return state; }); console.log(a);
return ( <> <div>detail페이지입니다.</div> </> ); }
(store.js)에서 initialState에 ajax로 가져온 json 데이터를 넣고 싶습니다. 그래서 state를 변경하기 위해 dispatch를 사용했는데 console.log(a) 에 데이터가 뜨지 않습니다 ㅠㅠ 도와주세요....
2023년 9월 2일 13:23 #96631
신혜원참가자(Detail.js) import { useSelector } from "react-redux";
function Detail() { let a = useSelector((state) => { return state; });
return ( <> <div>detail페이지입니다.</div> <p>{a.item}</p> </> ); }
export default Detail;
a를 html에 넣어보았는데 state변경이 잘 되지 않는 것 같습니다... 콘솔창에 이런 경고창이 뜨는데 혹시 이것때문일까요?
2023년 9월 2일 20:37 #96674
신혜원참가자shop.js에서는 useEffect 잘 동작하여 카테고리 아이템에 잘 들어갑니다! (shop.js)
import Category from "./Category"; import ProductList from "./ProductList"; import { useState, useEffect } from "react"; import axios from "axios"; import { changeItem } from "../../store"; import { useDispatch } from "react-redux"; function Shop({}) { const categoriesData = [ { name: "ALL", categories: null }, { name: "LIVING", categories: "living" }, { name: "WALKING", categories: "walking" }, { name: "CLEAN", categories: "clean" }, { name: "FOOD", categories: "food" }, ]; let [selectedCategory, setSelectedCategory] = useState(null); let handleCategorySelect = (type) => { setSelectedCategory(type); }; let [shopItems, setShopItems] = useState(); let dispatch = useDispatch();
useEffect(() => { axios .get( "https://raw.githubusercontent.com/mimkong/meongmeongdata/master/data.json" ) .then((result) => { setShopItems(result.data); dispatch(changeItem(result.data)); }) .catch(() => { console.log("json 데이터를 불러오는데 실패했습니다."); }); }, []);
return ( <> <h1>SHOP</h1> <Category categories={categoriesData} selectedCategory={selectedCategory} onSelectCategory={handleCategorySelect} /> <ProductList shopItems={ selectedCategory === null ? shopItems : shopItems.filter((item) => item.type === selectedCategory) } /> </> ); }
export default Shop;
혹시몰라 shop.js 전체코드 올립니다!!
-
글쓴이글
6 글 보임 - 1 에서 6 까지 (총 6 중에서)
- 답변은 로그인 후 가능합니다.