useSelector useDispatch

1. form.js

 import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { updateTel, updateName } from './action'

export default () => {
  const formData = useSelector(state => {
    console.log('--xia-', state);

    return state
  })
  console.log({formData});

  const dispatch = useDispatch()

  return 
form:
姓名: { dispatch(updateName(e.target.value)) }}/> 电话: { dispatch(updateTel(e.target.value)) }}/>
}
  1. formData拿到的是里面函数的返回值
  2. 在每次state变化的时候useSelector都会重新执行, 拿到的formData是基于state的订阅

2. main.js

import React from 'react';
import ReactDOM from 'react-dom';
// import App from './useReducer'
import Form from './form/form'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'

const store = configureStore()

ReactDOM.render(
    
        
, document.getElementById('app') );

3. configureStore.js

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import reducer from '../form/reducer'

export default () => {
  const middlewares = [thunk]
  const enhancers = applyMiddleware(...middlewares)
  const composedEnhancers = composeWithDevTools(...[enhancers])
  const store = createStore(reducer, composedEnhancers)
  return store
}

  1. enhancer是对store的增强,可以增强store的api
  2. redux中的中间件,比如thunk, 增强的是store.dispatch
  3. composedEnhancers 是一个洋葱模型,一个函数执行完,它的结果会当做上一个函数的入参

4. action.js

export const TYPES = {
  UPDATE_NAME: 'UPDATE_NAME',
  UPDATE_TEL: 'UPDATE_TEL'
}

export const updateTel = tel => {
  return {
    type: TYPES.UPDATE_TEL,
    payload: {tel}
  }
}

export const updateName = name => {
  return {
    type: TYPES.UPDATE_NAME,
    payload: {name}
  }
}

5. reducer.js

import reducerCreator from '../utils/redux'
import { TYPES } from './action'

const initalState = {
  tel: '',
  name: ''
}

export default reducerCreator(TYPES, initalState)

6. redux.js

// reducer 工厂函数
export default (TYPES, initialState) => {
  return (state, action) => {
    const {type, payload} = action

    if (Object.values(TYPES).includes(type))
      return {...state, ...payload}
    return state || initialState
  }
}

你可能感兴趣的:(useSelector useDispatch)