React-Redux 的用法

本文主题:如何在react中使用redux,为了在react中更方便的使用redux,作者封装了一个专门用于react的redux库,叫做react-redux。

react-redux 将所有的组件分成两部分,分别是UI组件和容器组件。
UI组件负责UI的实现,容器组件负责管理数据和逻辑。react-redux规定,所有的UI组件都是由用户提供的,容器组件则是由 React-Redux 自动生成。

1.connect()

connect的作用是将UI组件和容器组件连接起来。connect 主要作用有两点:
1.输入逻辑:将容器组件的state映射到UI组件的props
2.输出逻辑:将用户发出的action,传送到UI组件外面去

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)
function mapStateToProps(state, ownProps) {
    return {
    //将state.fetPubToolInfo中的数据映射到props中
        ...state.fetPubToolInfo
    };
}

mapStateToProps()函数:当容器组件中的state发生变化时,也会引起UI组件的重新渲染。connect方法可以不传该函数,这样Ui组件就不会订阅store组件的变化,store中state的变化不会引起Ui 组件的重新渲染。

function mapDispatchToPropos(dispatch, ownProps) {
    return {
        getDate: (message) => {
            dispatch(getDate(message));
        },
    };
}

mapDispatchToProps()函数:将dispatch行为映射到props中的某一个方法当中,执行props.getDate()就会执行dispatch方法来改变store中的state。

const mapDispatchToProps = {
  onClick: (filter) => {
    type: 'SET_VISIBILITY_FILTER',
    filter: filter
  };
}

2.Provider组件

Provider组件的作用是让所有组件都能拿到store中的数据。

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React-Redux是一个用于在React应用程序中管理状态的库。它结合了React和Redux,使得在React组件中使用Redux变得更加简单。 要使用React-Redux,首先需要安装它: ``` npm install react-redux ``` 然后,在你的应用程序中引入所需的模块: ```jsx import React from 'react'; import { Provider, useDispatch, useSelector } from 'react-redux'; import { createStore } from 'redux'; // 创建一个Redux store const store = createStore(reducer); // 创建一个React组件 const App = () => { // 使用useDispatch和useSelector钩子来访问Redux store const dispatch = useDispatch(); const state = useSelector(state => state); // 渲染组件 return ( <div> <h1>Hello React-Redux!</h1> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <p>Count: {state.count}</p> </div> ); }; // 渲染根组件并将Redux store传递给应用程序 ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` 在上面的示例中,我们首先创建了一个Redux store,然后使用`useDispatch`和`useSelector`钩子来访问Redux store。`useDispatch`用于触发action,`useSelector`用于选择需要的state。然后,在组件中,我们可以通过`dispatch`函数来分发action,以更新状态。最后,我们使用`Provider`组件将Redux store传递给整个应用程序。 这只是React-Redux的基本用法,它还提供了更多的功能和API来帮助你更好地管理状态。你可以参考React-Redux的官方文档来了解更多用法和示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值