一、react-redux作用
和redux和flux功能一样都是管理各个组件的状态,是redux的升级版。
二、为什么要用reac-redux?
那么我们既然有了redux,为什么还要用react-redux呢?原因如下:
1,解决了每个组件用数据时候都要引入store
2,自动实现UI组件和容器组件的分离
3,不需要通过事件订阅去告知组件数据更新(也就是省略了subscribe(),getState()两个方法)
三、使用:
1,安装react-redux
cnpm i react-redux -S
2,在根组件引入Provider组件,引入store,该组件上有个store属性,将引入的store赋值给他
3,在app组件引入需要开发的页面组件
4,在开发的组件中引入connect,通过高阶组件的方式将该组件和store连接起来。
而它有两个函数:mapStateToProps mapDispatchToProps
mapStateToProps :用于在页面渲染state中的数据,在组件中通过this.props.属性进行获取
mapDispatchToProps:用于在页面修改state中的数据,在组件中通过this.props.方法触发
然后在reducer页面中写自己要修改的代码逻辑,以上就是react-redux的理解与使用
完整代码如下
根组件的index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import store from './store/reactReduxStore';
import { Provider } from 'react-redux';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
app.js
import './App.css';
// import A from './a'
// import Todo from './todolist'
import One from './one';
// import Two from './Two';
// import Father from './Father';
import RouterALL from './routerALL';
import Header from './header';
import TodoReduxList from './store/todoReduxList'
import FzRedux from './store/fzRedux'
import ReactRedux from './reactRedux'
import { React, Fragment } from 'react';
function App() {
return (
<div className="App">
{/* <A></A>
<Todo></Todo>
<Father></Father> */}
{/* <Fragment>
<One></One>
<Two />
</Fragment> */}
{/* <RouterALL /> */}
{/* <Header /> */}
{/* <TodoReduxList></TodoReduxList> */}
{/* <FzRedux /> */}
<ReactRedux />
</div>
);
}
export default App;
页面组件代码:
import React from 'react'
import {connect} from 'react-redux'
class ReactRedux extends React.Component{
render(){
return(
<div>
{this.props.num}
<p><button onClick={this.props.handle.bind(this)}>修改数据</button></p>
</div>
)
}
}
// 通过映射的方式获取store中数据
const mapStateToProps = (state)=>({
num:state.reactReduxReducer.getIn(['n'])
})
//用于发送修改数据
const mapDispatchToProps = (dispatch)=>({
handle(){
let action = {
type:'ADD'
}
dispatch(action)
}
})
// 用高阶组件方法将组件与store映射 mapDispatchProps
export default connect (mapStateToProps,mapDispatchToProps) (ReactRedux)
store.js
import {legacy_createStore as createStore,combineReducers} from 'redux'
import reactReduxReducer from '../reducers/reactReduxReducer'
const reducer = combineReducers({
reactReduxReducer
})
const store = createStore(reducer)
export default store
reducer.js
import Immutable from "immutable";
const defaultState = Immutable.fromJS({
n:10
})
export default (state=defaultState,action)=>{
switch(action.type){
case 'ADD':
return state.updateIn(['n'],(x)=>++x)
}
return state
}