다음 JS 앱에 Redux 추가
19944 단어 nextreactreduxjavascript
먼저 다음 js 애플리케이션을 설정하십시오.
yarn create next-app next-redux
다음으로 원하는 패키지를 설치합니다.
yarn add redux redux-thunk next-redux-wrapper react-redux
설치 후 프로젝트의 루트에 redux 폴더를 만들고 해당 폴더 안에 types.js 및 store.js 파일을 추가하고 작업 및 리듀서를 위한 폴더도 추가합니다.
유형 파일에서 단일 유형을 추가해 보겠습니다. 사용자의 이름을 설정하기 위해
export const SET_NAME = "SET_NAME"
reducers 폴더에
main.js 파일을 추가합니다. 이 파일에서 앱의 기본 상태를 관리할 감속기를 만듭니다.이 파일에서 기본적으로 guest로 설정된 이름에 대한 값 하나만으로 기본 상태를 초기화합니다. 그런 다음 switch 문을 사용하여 전달된 동작과 값을 감지하고 수신된 값을 기반으로 상태가 업데이트됩니다.
import * as t from "../types";
const main = (state = {
name: "guest",
}, action) => {
switch(action.type){
case t.SET_NAME:
return {
...state,
name: action.payload
};
default:
return {...state};
}
}
export default main;
같은 리듀서 폴더에
rootReducer.js 파일을 추가합니다. 이 파일은 모든 리듀서를 하나로 결합합니다. 여러 개의 리듀서 파일이 있을 때 가장 유용합니다. 이 문서에서는 단일 리듀서 파일만 사용합니다. 메인 감속기.import { combineReducers } from "redux"
import main from "./main"
const rootReducer = combineReducers({
main: main
})
export default rootReducer;
다음으로
store.js 파일로 이동합니다.이 파일에서 우리는
redux 및 next-redux-wrapper 을 사용하여 redux 스토어를 생성하고, 상태에 새 값을 전달하기 전에 추가 기능을 사용할 수 있도록 redux-thunk 을 추가합니다.import { createStore, applyMiddleware, compose } from "redux"
import thunk from "redux-thunk"
import { createWrapper } from "next-redux-wrapper"
import rootReducer from "./reducers/rootReducer"
const middleware = [thunk]
const makeStore = () => createStore(rootReducer, compose(applyMiddleware(...middleware)))
export const wrapper = createWrapper(makeStore)
이제 이름 설정 작업을 만들고 작업 폴더에
main.js 파일을 만듭니다. 그 안에 새 이름 값으로 설정 이름 유형을 지정하는 기능이 있습니다.import * as t from "../types";
import axios from "axios";
import { request } from "../../util/request";
export const setInfo = (name) => dispatch => {
dispatch({
type: t.SET_NAME,
payload: name
});
}
이 모든 작업을 완료한 후 디렉토리는 아래와 같아야 합니다.
이제
_app.js 파일로 이동하면 다음과 같이 표시됩니다.import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
다음과 같이 업데이트하십시오.
import React from "react"
import { wrapper } from "../redux/store"
const MyApp = ({ Component, pageProps}) => (
<Component {...pageProps} />
)
export default wrapper.withRedux(MyApp);
스토어 파일에서 만든 redux 래퍼에 앱을 래핑하고 소품을 전달했습니다.
index.js 에서 모든 페이지 콘텐츠를 꺼내고 이름을 묻는 입력 상자를 남겨 둡니다.return (
<div className={styles.container}>
<p>Enter a Name :</p>
<input
type="text">
</input>
<button>
Submit
</button>
</div>
)
다음으로
useState을 사용하여 양식의 값을 업데이트하고 저장하기 위한 상태 관리를 추가합니다. 또한 인덱스 페이지를 redux 상태에 연결하고 마지막으로 mapDispatchToProps을 사용하여 작업을 연결하고 mapStateToProps을 사용하여 상태를 연결합니다. 최종 index.js은 다음과 같아야 합니다.import { useState } from 'react'
import { connect } from "react-redux"
import { setInfo } from "../redux/actions/main"
import styles from '../styles/Home.module.css'
function Home(props) {
const { name, setInfo } = props
const [newName, setName] = useState("")
return (
<div className={styles.container}>
<p>Enter a Name {name}:</p>
<input
type="text"
value={newName}
onChange={(e) => setName(e.target.value)}>
</input>
<button onClick={() => setInfo(newName)}>
Submit
</button>
</div>
)
}
const mapStateToProps = state => {
return { name: state.main.name }
}
const mapDispatchToProps = {
setInfo
}
export default connect(mapStateToProps, mapDispatchToProps)(Home)
Redux Dev Tools 으로 디버깅할 수 있으려면
store.js 코드를 다음으로 업데이트하십시오.import { createStore, applyMiddleware, compose } from "redux"
import thunk from "redux-thunk"
import { createWrapper } from "next-redux-wrapper"
import rootReducer from "./reducers/rootReducer"
const middleware = [thunk]
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const enhancer = composeEnhancers(applyMiddleware(...middleware));
const makeStore = () => createStore(rootReducer, enhancer)
export const wrapper = createWrapper(makeStore)
이제 홈페이지가 아래 이미지와 같아야 하며 이름을 변경하면 "손님"값이 업데이트됩니다.
이 기사가 도움이 된다면 Full Stack Next JS Course on Udemy에서 다른 Next JS 비디오를 확인할 수도 있습니다.
Reference
이 문제에 관하여(다음 JS 앱에 Redux 추가), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/theallegrarr/adding-redux-to-next-js-app-4n5o텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)