博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react-redux 的使用
阅读量:7237 次
发布时间:2019-06-29

本文共 2085 字,大约阅读时间需要 6 分钟。

1 安装react-redux: npm install --save react-redux 

2.之前使用redux的store.subscribe监听 store的状态改变,通过store.getState函数获取store的状态值;并且需要划分ui组件和聪明组件,着实很麻烦,引入react-redux,可以改变这一切;

store定义如下,引入react-redux:

import { createStore, compose, applyMiddleware } from 'redux';import thunk from 'redux-thunk';import reducer from './reducer';const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;const store = createStore(reducer, composeEnhancers(    applyMiddleware(thunk)));export default store;

3. 顶部组件在最外层引入store,这样所有的组件都可以使用store了;

import React from 'react';import ReactDOM from 'react-dom';import App from './App';import { Provider } from 'react-redux'import store from './store'const MyApp = (    
)ReactDOM.render(MyApp, document.getElementById('root'));

4.具体在组件中使用connect将 ui组件变成聪明组件:

import React, { Component } from 'react';import './App.css';import { connect } from 'react-redux'import {changeInputValue,addInputValue,deleteListItem,getListData} from './store/actionCreator.js'class App extends Component {  constructor(props){    super(props);    this.state = {}  }  componentDidMount(){    this.props.getListDatas();  }  render() {    const {inputValue,changeInputValue,addListItem,list,deleteList} = this.props;    return (      
    { list.map((item,index) => { return (
  • {item}
  • ) }) }
); }}const mapStateToProps = (state)=> { return ( { inputValue:state.inputValue, list:state.list } )};const mapDispatchToProps = (dispatch)=>{ return { changeInputValue(e){ dispatch(changeInputValue(e.target.value)) }, addListItem(){ dispatch(addInputValue()) }, deleteList(index){ dispatch(deleteListItem(index)) }, getListDatas(){ dispatch(getListData()) } }}export default connect(mapStateToProps,mapDispatchToProps)(App);

 

转载于:https://www.cnblogs.com/xiaozhumaopao/p/10548370.html

你可能感兴趣的文章
mysql #1062 – Duplicate entry '1′ for key ‘PRIMARY'
查看>>
【转载】小小的公共库,大大的耦合,你痛过吗?
查看>>
图的遍历(深度优先搜索法和广度优先搜索法)
查看>>
PhoneGap & HTML5 学习资料网址
查看>>
机器学习相关——协同过滤
查看>>
2017年软件工程第四次作业-3四则运算
查看>>
userDefaults
查看>>
再来写一个随机数解决方案,对Random再来一次封装
查看>>
最近要租房子,用Python看一下房源吧..
查看>>
系数矩阵存储
查看>>
文件上传(java web)
查看>>
在线更新问题 HDU5877 线段树
查看>>
codevs1260 快餐问题
查看>>
Algs4-1.3.43文件列表
查看>>
类和对象
查看>>
[转] 深入浅出mongoose-----包括mongoose基本所有操作,非常实用!!!!!
查看>>
CSS创建三角形(小三角)的几种方法
查看>>
Python简单基础小程序
查看>>
Python 购物车练习 2.0
查看>>
Hdoj 4089
查看>>