Redux进阶

博客介绍了UI组件、容器组件和无状态组件,UI组件负责渲染,容器组件负责逻辑。还提及redux - thunk中间件,安装后可升级dispatch方法拆分异步逻辑;以及react - redux,安装后方便在react使用redux,通过Provider和connect关联store与组件。

UI组件和容器组件

UI组件:只负责页面渲染,没有或极少有逻辑处理

容器组件:负责页面逻辑,将UI组件作为子组件集成进来

无状态组件:是一个函数,将只有render函数的UI组件简化成无状态组件,可提高性能


redux-thunk中间件

安装:npm install redux-thunk --save

在store/index.js中进行使用

import { createStore, applyMiddleware } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'

const store = createStore(reducer, applyMiddleware(thunk))

export default store

使用了redux-thunk后,会对dispatch方法进行升级,action可以是一个函数

进而将Ajax异步逻辑拆分出来,放到action中进行操作,而redux-saga是拆分到一个新文件中进行管理

①当action是一个对象时,通过store的dispatch方法会直接把action传到store,在传给reducer

②当action是一个函数时,通过store的dispatch方法会执行这个函数,并将dispatch方法作为参数传递进去

//声明
const getInitAction = (list) => ({
    type: INIT_LIST,
    list
})
export const getAjaxAction = () => {
    return (dispatch) => {
        axios.get('/api/list.json').then((res) => {
            const list = res.data.list
            const action = getInitAction(list)
            dispatch(action)
        })
    }
}
//调用
componentDidMount() {
    const action = getAjaxAction()
    store.dispatch(action)
}

react-redux

安装:npm install react-redux --save

作用:方便在react使用redux

①在入口文件中引入Provider提供器,绑定store,即可将store提供给所有子组件

import TodoListRR from './TodoListRR'
import { Provider } from 'react-redux'
import store from './storeRR'

const App = (
    <Provider store={store}>
        <TodoListRR />
    </Provider>
)

ReactDOM.render(App, document.getElementById('root'));

②在组件中,用react-redux提供的connect方法将store和组件关联起来

<input value={this.props.inputValue} onChange={this.props.handleInputChange} />

const mapStateToProps = (state) => {
    return {
        inputValue: state.inputValue
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        handleInputChange(e) {
            const action = {
                type: 'change_input_value',
                value: e.target.value
            }
            dispatch(action)
        }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoListRR)
//connet方法将数据mapStateToProps、逻辑mapDispatchToProps和UI组件TodoListRR结合成容器组件

转载于:https://my.oschina.net/startjcu/blog/3051810

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值