Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Folder structure
- */
- src
- -- redux
- -- -- action
- -- -- -- builder.js
- -- -- -- counter.js
- -- -- reducer
- -- -- -- builder.js
- -- -- -- counter.js
- -- -- -- rootReducer.js
- /**
- * 1. Create the reducer: reducer/builder.js
- */
- // Use immer for create the next immutable state tree by simply modifying the current tree.
- import produce from 'immer';
- // The state should always be defined.
- const initialState = {
- arr: ""
- }
- export default function builder (state = initialState, action) {
- console.log('reducer', state, action)
- switch(action.type) {
- case 'PUSH':
- return produce(state, draft => {
- draft.arr += 'X'
- })
- case 'SLICE':
- return produce(state, draft => {
- draft.arr = draft.arr.substring(0, draft.arr.length-1)
- })
- case 'CLEAR':
- return produce(state, draft => {
- draft.arr = ""
- })
- default:
- return state
- }
- }
- /**
- * 2. Create the action creators and types: action/builder.js
- */
- /**
- * Action Types
- * Sometimes it's a good idea to put them in a seperate file.
- */
- export const PUSH = 'PUSH'
- export const SLICE = 'SLICE'
- export const CLEAR = 'CLEAR'
- /**
- * Action Creators
- */
- export function push () {
- return {
- type: PUSH
- }
- }
- export const slice = () => {
- return {
- type: SLICE
- }
- }
- export const clear = () => ({ type: CLEAR })
- /**
- * 3. Register the reducer at the rootReducer: reducer/rootReducer.js
- */
- import { combineReducers } from "redux";
- import counter from "./counter"
- import builder from "./builder"
- export default combineReducers({
- counter,
- builder
- });
- /**
- * 4. Connect your components: Builder.js
- */
- import React from 'react'
- import { connect } from 'react-redux'
- import { push, slice, clear } from './redux/actions/builder'
- const mapStateToProps = (state) => {
- return {
- arr: state.builder.arr,
- }
- }
- const mapDispatchToProps = {
- push,
- slice,
- clear
- }
- function Builder (props) {
- // const [count, setCount] = useState(0)
- // now count is part of the state (this.state.count)
- // not a setter is available: setCount(0)
- // useState(<initialValue>)
- const _push = () => {
- props.push()
- }
- const _slice = () => {
- props.slice()
- }
- const _clear = () => {
- props.clear()
- }
- return (
- <div>
- <h2>Builder</h2>
- <div>
- <button onClick={_slice}>-</button>
- <span>{props.arr}</span>
- <button onClick={_push}>+</button>
- </div>
- <div>
- <button onClick={_clear}>Reset</button>
- </div>
- </div>
- )
- }
- export default connect(mapStateToProps, mapDispatchToProps)(Builder)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement