전역으로 상태관리를 할 수 있는 이점을 이용하고 싶어 배우는 Redux
Using CRA for using webpack
npm i redux
// or
yarn add redux
-
- Place where saving data
import { createStore } from "redux";
const reducer = () => {};
const store = createStore(reducer);
-
- Function for modifying data
- Return data is application's data
const modifyier = (state = 0) => {
// modifying state ...
return state;
};
const store = createStore(modifyier);
console.log(store.getState());
-
- Only modifyier can change own store's data
- Modifyier's 2nd prop is action
- Action must be object type
const modifyier = (state, action) => {
if (action.type === "SOMETHING") {
return "SOMETHING";
} else {
return "INIT";
}
};
const store = createStore(modifyier);
// current state === "INIT"
store.dispatch({ type: "SOMETHING" });
// current state === "SOMETHING"
-
- Subscribe detect change
const onChange = () => {
console.log("Im changed!");
};
store.subscribe(onChange);
-
-
- only waty to change the state is sending action
-
- don't return mutated state, return new state
// return state.push("something"); return [...state, { text: "something" }];
-
- return action object
const returnAction = (something) => ({ type: SOME_TYPE, data: something });
//somewhere
store.dispatch(returnAction(data));
npm i react-redux
// store/store.js
import { createStore } from "redux";
const ADD = "ADD";
const DELETE = "DELETE";
const reducer = (state = [], action) => {
switch (action.type) {
case ADD:
return [{ text: action.text, id: Date.now() }, ...state];
case DELETE:
return state.filter((toDo) => toDo !== action.id);
default:
return state;
}
};
const store = createStore(reducer);
export default store;
const addToDo = (text) => {
return { type: ADD, text };
};
const deleteToDo = (id) => {
return { type: DELETE, id };
};
// index.js
...
import { Provider } from "react-redux";
import store from "./store/store";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
- give Store's state to component, using connect function
...
import { connect } from "react-redux";
const Compo = (props) => {
console.log(props);
// it comes {...ownProps, toDos: state}
// because function mapStateToProps return {toDos: state}
...
}
const mapStateToProps(state, ownProps) {
console.log(state, ownProps);
// state is redux store's state
// ownProps is Compo's props
return {toDos: state};
}
export default connect(mapStateToProps) (Compo);
- give Dispatch function to component, using connect function
const Home = ({ addToDo }) => {
// using actionCreator addToDo
}
const mapDispatchToProps(dispatch, ownProps) {
return {addToDo: (text) => dispatch(actionCreator(text))}
}