美文网首页
React-redux学习记录

React-redux学习记录

作者: 十国 | 来源:发表于2020-11-05 18:54 被阅读0次

插件集成

    yarn add redux react-redux redux-thunk redux-logger

版本
    "react": "16.13.1",
    "react-native": "0.63.3",
    "react-redux": "^7.2.2",
    "redux": "^4.0.5",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.3.0"

目录结构

|-- root
    |-- node_modules
    |-- ios
    |-- android
    |-- index.js
    |-- App.js
    |-- app
        |-- redux
            |-- actions.a.js
            |-- actions.async.js
            |-- actions.b.js
            |-- actions.c.js
            |-- acitons.index.js
            |-- reducers.a.js
            |-- reducers.b.js
            |-- reducers.index.js
            |-- store.js
            |-- types.js
        |-- index.class.js
        |-- index.hooks.js
        |-- index.hooks.use.js

上代码

  • store.js
import {createStore,applyMiddleware} from 'redux';
import reducer from './reducers.index';
import thunk from 'redux-thunk'
import logger from 'redux-logger'
let store = createStore(
    reducer,
    applyMiddleware(thunk,logger)
);//传入reducer
// let state = store.getState()
// console.log('sg state',state)
export default store;
  • types.js
export const ADD = 'ADD'
//更改待办项的完成状态
export const TOGGLE_COMPLETE = 'TOGGLE_COMPLETE';

export const THEME_COLOR = 'THEME_COLOR';
//异步
export const THEME_COLOR_ASYNC = 'THEME_COLOR_ASYNC';

export const FONT_ADD = 'FONT_ADD';

export const FONT_20 = 'FONT_20';

export const FONT_FREE = 'FONT_FREE';
  • reducers.index.js
import { combineReducers } from 'redux'
import a from './reducers.a'
import b from './reducers.b'
export default combineReducers({
  a,
  b,
})
  • reducers.a.js
import { ADD, TOGGLE_COMPLETE } from './types'
//定义默认状态(默认数据:我的待办)
let initState = {
  todos: [
    {
      id: parseInt(Math.random() * 10000000),
      isComplete: false,
      title: '学习redux'
    }, {
      id: parseInt(Math.random() * 10000000),
      isComplete: true,
      title: '学习react'
    }, {
      id: parseInt(Math.random() * 10000000),
      isComplete: false,
      title: '学习node'
    }
  ]
};


function reducer(state = initState, action) {
  switch (action.type) {
    case ADD:
      return {
        todos: [
          ...state.todos,
          action.payload
        ]
      }

    case TOGGLE_COMPLETE:
      return {
        todos: state.todos.map(item => {
          if (item.id === action.payload) {
            item.isComplete = !item.isComplete
          }
          return item
        })
      }
    default:
      return state
  }
}
export default reducer;
  • reducers.b.js
import { THEME_COLOR, THEME_COLOR_ASYNC, FONT_FREE, FONT_20, FONT_ADD } from './types'
//定义默认状态(默认数据:我的待办)
let initState = {
  backgroundColor: 'red',
  font: 14,
};


function reducer(state = initState, action) {
  switch (action.type) {
    case THEME_COLOR:
    case THEME_COLOR_ASYNC:
      return {
        ...state,
        backgroundColor: action.payload
      }
    case FONT_ADD:
      return {
        ...state,
        font: state.font+1
      }
    case FONT_20:
      return {
        ...state,
        font: 20
      }
    case FONT_FREE:
      return {
        ...state,
        font: action.payload
      }

    default:
      return state
  }
}
export default reducer;
  • actions.index.js
import a from './actions.a'
import b from './actions.b'
import async from './actions.async'
import c from './actions.c'

// console.log('sg c',c)
export default {
    a,
    b,
    async,
    c,
}
  • actions.a.js
import { ADD, TOGGLE_COMPLETE } from './types'

let actions = {
    addTodo: function (payload) {
        return { type: ADD, payload };
    },
    //更改完成状态,此处payload传id
    toggleComplete: function (payload) {
        return { type: TOGGLE_COMPLETE, payload };
    },
};

export default actions;//导出ActionCreators
  • actions.async.js
import { THEME_COLOR_ASYNC } from './types'
let actions = {
    setThemeColorAsync: function (payload) {
        return dispatch => {
            setTimeout(() => {
                let action = { type: THEME_COLOR_ASYNC, payload };
                dispatch(action)
            }, 3000)
        }
    }
};
export default actions;//导出ActionCreators
  • actions.b.js
import {THEME_COLOR } from './types'

let actions = {
    setThemeColor: function (payload) {
        return { type: THEME_COLOR, payload };
    }
};

export default actions;//导出ActionCreators
  • actions.c.js
import { FONT_ADD, FONT_20, FONT_FREE } from './types'
export const action_font_add = () => {
    return {
        type: FONT_ADD,
    }
}

export const action_font_20 = () => ({
    type: FONT_20,
})
export const action_font_free = (payload) => ({
    type: FONT_FREE,
    payload
})


export default {
    action_font_add,
    action_font_20,
    action_font_free,
}
  • App.js
import React from 'react';
import { Provider } from 'react-redux'
import Page from './app/index.class'
// import Page from './app/index.hooks.use'
// import Page from './app/index.hooks'
import store from './app/redux/store'
export default function App() {
  return (
    <Provider store={store}>
      <Page />
    </Provider>
  )
}
  • index.class.js
import React from 'react';
import { View, Text, StyleSheet, Button, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux'
class App extends React.Component {

  render() {
    console.log('sg App', this.props)
    return (
      <View style={{ ...styles.container, backgroundColor: this.props.backgroundColor }}>
        <Text style={{ fontSize: this.props.font }}>父视图</Text>
        <TodoListWidget />
      </View>
    )
  }
}

let index = connect((state) => ({
  backgroundColor: state.b.backgroundColor,
  font: state.b.font,
}))(App)
export default index;


class TodoList extends React.Component {

  render() {
    console.log('sg TodoList', this.props)
    return (
      <View style={{ backgroundColor: 'white' }}>
        <Text>[我的待办]子组件</Text>
        {
          this.props.todos.map((i, index) => {
            return (
              <TouchableOpacity key={`sg--TodoList-${index}`} style={{ marginVertical: 5, backgroundColor: 'cyan' }}
                onPress={() => {
                  this.props.a.toggleComplete(i.id)
                }}
              >
                <Text>{i.id}</Text>
                <Text>{i.title}</Text>
                <Text>{i.isComplete ? '完成' : '未完成'}</Text>
              </TouchableOpacity>
            )
          })
        }

        <Button
          title="添加待办"
          onPress={() => {
            this.props.a.addTodo({
              id: parseInt(Math.random() * 10000000),
              isComplete: false,
              title: `学习${Math.random()}`
            })
          }}
        />


        <Button title="console.log(this.props)"
          onPress={() => {
            console.log(this.props)
          }}
        />

        <Button title="修改父视图背景色"

          onPress={() => {
            this.props.b.setThemeColor('yellow')
          }}
        />
        <Button title="async修改父视图背景色"
          onPress={() => {
            this.props.async.setThemeColorAsync('pink')
          }}
        />
        <Button title="修改父视图文字大小"
          onPress={() => {
            this.props.c.action_font_free(50)
          }}
        />
      </View>
    )
  }
}

import actions from './redux/actions.index'
import { bindActionCreators } from 'redux'
let mapStateToProps = (state, ownProps) => {
  // console.log('sg mapStateToProps state=', state, 'ownProps', ownProps)
  return {
    todos: state.a.todos
  }
}
let mapDispatchToProps = (dispatch, ownProps) => {
  // console.log('sg mapDispatchToProps dispatch=', dispatch, 'ownProps=', ownProps)
  // return bindActionCreators({ ...actions.a, ...actions.b }, dispatch)
  return {
    a: bindActionCreators(actions.a, dispatch),
    b: bindActionCreators(actions.b, dispatch),
    async: bindActionCreators(actions.async, dispatch),
    c: bindActionCreators(actions.c, dispatch),
  }
}


let TodoListWidget = connect(mapStateToProps, mapDispatchToProps)(TodoList)



const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 100,
  },
});
  • index.hooks.js
import React from 'react';
import { View, Text, StyleSheet, Button, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
function App(props) {
  console.log('App', props)
  const { b } = props
  return (
    <View style={{ ...styles.container, backgroundColor: b.backgroundColor }}>
      <Text style={{ fontSize: b.font }}>父视图</Text>
      <WidgetTodoList />
    </View>
  )
}

let mapStateToProps = (state) => ({
  b: state.b
})
export default connect(mapStateToProps)(App)




import actions from './redux/actions.index'
function TodoList(props) {
  console.log('TodoList', props)
  const { todos, a, b, async ,c} = props
  return (
    <View >
      <Text>[我的待办]子组件</Text>
      {
        todos.map((i, index) => {
          return (
            <TouchableOpacity key={`sg--TodoList-${index}`} style={{ marginVertical: 5, backgroundColor: 'cyan' }}
              onPress={() => {
                a.toggleComplete(i.id)
              }}
            >
              <Text>{i.id}</Text>
              <Text>{i.title}</Text>
              <Text>{i.isComplete ? '完成' : '未完成'}</Text>
            </TouchableOpacity>
          )
        })
      }

      <Button
        title="添加待办"
        onPress={() => {
          a.addTodo({
            id: parseInt(Math.random() * 10000000),
            isComplete: false,
            title: `学习${Math.random()}`
          })
        }}
      />


      <Button title="console.log(props)"
        onPress={() => {
          console.log(props)
        }}
      />

      <Button title="修改父视图的背景色"
        onPress={() => {
          b.setThemeColor('green')
        }}
      />

      <Button title="async修改父视图背景色"
        onPress={() => {
          async.setThemeColorAsync('purple')
        }}
      />

      <Button title="修改父视图文字大小"
        onPress={() => {
          c.action_font_free(50)
        }}
      />
    </View>
  )
}


let mapStateToPops2 = (state) => ({
  todos: state.a.todos,
})
let mapDispatchToProps2 = (dispatch) => ({
  a: bindActionCreators(actions.a, dispatch),
  b: bindActionCreators(actions.b, dispatch),
  async: bindActionCreators(actions.async, dispatch),
  c: bindActionCreators(actions.c, dispatch),
})
const WidgetTodoList = connect(mapStateToPops2, mapDispatchToProps2)(TodoList)

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 100,
  }
});

  • index.hooks.use.js
import React from 'react';
import { View, Text, StyleSheet, Button, TouchableOpacity } from 'react-native';

export default function App() {
  let b = useSelector(state => state.b)
  return (
    <View style={{ ...styles.container, backgroundColor: b.backgroundColor }}>
      <Text style={{ fontSize: b.font }}>父视图</Text>
      <TodoList />
    </View>
  )
}


import actions from './redux/actions.index'
import { useSelector, useDispatch } from 'react-redux'
function TodoList() {
  let todos = useSelector(state => state.a.todos)
  let dispatch = useDispatch()
  return (
    <View >
      <Text>[我的待办]子组件</Text>
      {
        todos.map((i, index) => {
          return (
            <TouchableOpacity key={`sg--TodoList-${index}`} style={{ marginVertical: 5, backgroundColor: 'cyan' }}
              onPress={() => {
                dispatch(actions.a.toggleComplete(i.id))
              }}
            >
              <Text>{i.id}</Text>
              <Text>{i.title}</Text>
              <Text>{i.isComplete ? '完成' : '未完成'}</Text>
            </TouchableOpacity>
          )
        })
      }

      <Button
        title="添加待办"
        onPress={() => {
          dispatch(actions.a.addTodo({
            id: parseInt(Math.random() * 10000000),
            isComplete: false,
            title: `学习${Math.random()}`
          }))
        }}
      />


      <Button title="console.log(todos, dispatch, actions)"
        onPress={() => {
          console.log(todos, dispatch, actions)
        }}
      />

      <Button title="修改父视图的背景色"
        onPress={() => {
          dispatch(actions.b.setThemeColor('green'))
        }}
      />

      <Button title="async修改父视图背景色"
        onPress={() => {
          dispatch(actions.async.setThemeColorAsync('purple'))
        }}
      />

      <Button title="修改父视图文字大小"
        onPress={() => {

          dispatch(actions.c.action_font_add())
        }}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 100,
  }
});

相关文章

  • React-redux学习记录

    插件集成 目录结构 上代码 store.js types.js reducers.index.js reducer...

  • React(五)

    React-redux(三):connect和mapStateToProps React-redux(四):map...

  • react-redux 使用记录

    安装依赖 创建 action 文件 action 对象 action 本质是一个 JS 对象,是 store 数据...

  • react-redux学习

    react-redux的作用 1、避免redux中store全局化,把store直接继承到react应用的顶层pr...

  • redux的简单应用

    1、安装 redux和react-redux: npm i redux react-redux --save-de...

  • react-redux简介(二)源码解析

    写在开头 前置知识内容,react、react-redux。 react-redux文档:https://www....

  • react-redux

    react-redux 相关步骤 npm install react-redux --save 在项目中导入re...

  • 【React进阶系列】手写实现react-redux api

    简介:简单实现react-redux基础api react-redux api回顾 把store放在context...

  • react-redux

    使用react-redux,可以更方便的使用redux开发 先install react-redux使用react...

  • react-redux

    redux 全局状态管理 react-redux 优化模块 优化redux的使用过程 通过react-redux ...

网友评论

      本文标题:React-redux学习记录

      本文链接:https://www.haomeiwen.com/subject/ydjavktx.html