React Redux에서 구성 요소 간의 값 공유를 수행하는 경우 참고
개요
새해 일찍 React Redux를 시도하고 싶다고 생각하고, 여러가지 조사하는 중 문득 컴퍼넌트간의 값 공유는 어떻게 할까라고 생각해 만들어본 샘플의 메모입니다. 또한 React Redux의 구조 등에 대해서는 @erukiti 씨의 기사 React+Redux 입문 이나 서적 React 입문 React · Redux 도입부터 서버 측 렌더링으로 UX 향상까지
예제
아래와 같이 텍스트 박스에 입력하는 컴퍼넌트, 입력한 내용을 표시하는 컴퍼넌트로 나눌 때에 값의 공유를 실시하는 샘플을 기재합니다.

샘플 소스
index.js
InputApp이 입력 부분이고 ViewApp이 표시 부분이 됩니다.
index.js
import React from 'react';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import {render} from 'react-dom';
import inputReducer from './reducers/input';
import InputApp from './containers/InputApp';
import ViewApp from './containers/ViewApp';
const store = createStore(inputReducer);
render(
<Provider store ={store}>
<InputApp />
<ViewApp />
</Provider >,
document.getElementById('root')
);
containers
InputApp.js
import {connect} from 'react-redux';
import InputApp from '../components/InputApp';
import {inputName} from '../actions/input';
function mapStateToProps({name}) {
return {name};
}
function mapDispatchToProps(dispatch) {
return {
inputName(name) { dispatch(inputName(name)); }
};
}
export default connect(mapStateToProps, mapDispatchToProps)(InputApp);
ViewApp.js
import {connect} from 'react-redux';
import ViewApp from '../components/ViewApp';
function mapStateToProps({name}) {
return {name};
}
export default connect(mapStateToProps)(ViewApp);
components
InputApp.js
import React from 'react';
export default function InputApp({name, inputName}){
return (
<div>
【名前】
<input type ="text" onChange = {(e) => inputName(e.target.value)} />
</div>
);
}
ViewApp.js
import React from 'react';
export default function ViewApp({name}){
return (
<div>
【名前】{name}
</div>
);
}
액션
input.js
export const inputName = (name) => (
{ type: 'INPUT_NAME', payload: {name} }
);
reducers
input.js
const initialState = { name: ''};
export default function inputReducer(state = initialState, action) {
switch (action.type) {
case 'INPUT_NAME':
return { ...state, name: action.payload.name};
default:
return state;
}
}
Reference
이 문제에 관하여(React Redux에서 구성 요소 간의 값 공유를 수행하는 경우 참고), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/someone7140/items/7a8d7de63be652ba90d6텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)