react-redux
和redux一样效果,不同实现
安装
cnpm install react-redux --save
cnpm install redux --save
引入
import {createStore} from 'redux';
import {Povider,connect} from 'react-redux'
1、创建仓库
//state为初始数据,action内包含对初始数据进行逻辑判断的参数,需要dispatch传入/修改
function reducer(state={num:0},action)
{
switch(action.type)
{
case 'add':
state.num++;
break;
default:
break;
}
return {...state}
}
const store=createStore(reducer);
2、创建映射仓库state的方法,即使得和组件关联后,可以通过props获取
//state为固定形参
function xx(state)
{
//返回后,使得将value绑定到props上,即可通过value获取state
return{
value:state.num
}
}
3、创建映射修改state数据的方法,即使得和组件关联后,可以通过props获取
//dispatch为固定形参
function xxx(dispatch)
{
return {
//返回后,使得将onAddClick绑定到props上,即可通过OnAddclick修改action,从而修改state
onAddClick:()=>{dispatch({传入action中的键值对})}
}
}
4、将映射方法和组件关联,使得方法绑定到组件props上,并返回一个新组件
const Apps=connect(
xx,
xxx
)(组件名这里为Counter)
5、渲染视图并更新,同时将store和新组件关联
ReactDOM.render(<Provider store={store}>
<Apps />
</Provider>
, document.getElementById('root'));
代码示例:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {createStore} from 'redux';
//将数据和视图集合在一起
import {Provider,connect} from 'react-redux'
const addAction={
type:'add'
}
function reducer(state={num:0},action)
{
switch(action.type)
{
case 'add':
state.num++;
break;
default:
break;
}
return {...state}
}
//将state映射到props
function toProps(state)
{
return{
value:state.num
}
}
//将修改state数据的方法,映射到props
function toDispatch(dispatch)
{
return {
onAddClick:()=>{dispatch(addAction)}
}
}
class Counter extends React.Component{
render()
{
//计数,通过store的state传递给props
const value=this.props.value
//将修改数据的方法传入
const onAddClick=this.props.onAddClick
return(
<div>
<h1>数量:{value}</h1>
<button onClick={onAddClick}>事件加1</button>
</div>
)
}
}
const store=createStore(reducer);
//将映射方法关联到一个组件上
//可以理解为该组件调用方法,将方法的返回值绑定到props上
const Apps=connect(
toProps,
toDispatch
)(Counter)
//渲染视图并更新,将store里的state和组件关联
ReactDOM.render(<Provider store={store}>
<Apps />
</Provider>
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();