版权声明:非经本人同意,请勿转载。 https://blog.csdn.net/QQ_Empire/article/details/82466938
1、安装redux 命令:npm i redux -D
2、src中新建 View.js Action.js Store.js Reducer.js
3、逻辑构建
4、在home页面登录获取用户名步骤:
在home组件,状态设置:str:Store.getState()
View.js
import React from 'react';
import Action from './Action'
import Store from './Store'
class Demo extends React.Component{
constructor(props){
super(props)
this.state={
//获取当前时间点的数据集合state
str:Store.getState()
}
this.itemchange=this.itemchange.bind(this)
}
itemchange(){
//获取当前时间点的数据集合state
var data=Store.getState();
this.setState({str:data})
}
componentDidMount(){
//一旦状态改变,就执行绑定的函数;方法返回一个函数,调用可以解除监听
Store.subscribe(this.itemchange)
}
tap(){//修改状态的唯一方式就是dispatch一个action,store接收到action后自动调用reducer
Store.dispatch(Action(this.refs.ipt.value))
}
render(){
return(
<div>
<h1>redux</h1>
<input type="text" ref="ipt"/>
<button onClick={this.tap.bind(this)}>添加</button>
<hr/>
{
this.state.str.map((item,i)=>{
return (
<div key={i}>
{item}
</div>
)
})
}
</div>
)
}
}
export default Demo;
Action.js
const Action=function(text){
return{
type:"ADD_TODO",
text:text
}
}
export default Action;
Store.js
import {createStore} from 'redux';
import Reducer from './Reducer';
const Store=createStore(Reducer)
export default Store;
reducer.js
const Reducer=function(state,action){
if(typeof state === 'undefined'){
return []
}
switch (action.type){
case 'ADD_TODO':
return [...state,action.text]
break;
default:
return state;
break;
}
}
export default Reducer;
扫描二维码关注公众号,回复:
3167585 查看本文章