我是靠谱客的博主 神勇寒风,最近开发中收集的这篇文章主要介绍redux学习笔记(1)- 初学,单纯的用react和redux,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1,引入react + react-dom + redux

import
React
from 'react'
import { render } from 'react-dom'
import { createStore,combineReducers} from 'redux'

2,创建一个状态处理机reducer函数(reducer是纯函数,专门用于处理state),并用combine链接起来(如果是多个reducer可以都连接起来)成为状态处理机组rootReducer

function addItem(state = [], action) {
switch (action.type) {
case 'ADD_ITEM':
return [action.text, ...state]
case 'DEL_ITEM':
state.splice(action.key,1)
return state
default:
return state
}
}
const rootReducer = combineReducers({
addItem
})

3,生成store,绑定rootReducer,第二个参数是为了绑定redux_devtools扩展

const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())

4,定义react组件和调用方法

class Home extends React.Component{
addhandle(data){ //新增方法
store.dispatch({ type: 'ADD_ITEM', text: this.textInput.value});
}
delhandle(d){ //删除方法
store.dispatch({ type: 'DEL_ITEM', key: d });
}
render(){
const itemList = store.getState().addItem || []; //获取重新得到的item数据
return (
<div>
<h4>hello world!</h4>
<input type="text" ref={(input) => { this.textInput = input; }} /><button onClick={this.addhandle.bind(this)}>增加</button>
<ul>
{
itemList.map((k,i)=>{
return <li key={i}>第{i}条内容是:{k} <a onClick={this.delhandle.bind(this,i)}>删除</a></li>
})
}
</ul>
</div>
)
}
}

5,渲染组件,并绑定store.subscribe

const xuanran = () => {
render(
<Home />,
document.getElementById('content')
)
}
store.subscribe(xuanran)//绑定到xuanran函数上。
xuanran()//执行渲染

最后

以上就是神勇寒风为你收集整理的redux学习笔记(1)- 初学,单纯的用react和redux的全部内容,希望文章能够帮你解决redux学习笔记(1)- 初学,单纯的用react和redux所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部