安装
yarn add react-redux
创建文件、文件夹
|- redux
|- actions.js
|- reducer.js
|- store.js
actions.js
export const change_user_info = "changeUserInfo"
export function ChangeUserInfo( data ){
return {
type: change_user_info,
data: data
}
}
reducer.js
import { change_user_info } from "./actions"
let storeState = {
userInfo: null
}
export default function Store( state = storeState, actions ){
switch( actions.type ){
case change_user_info:
return { ...state, userInfo: actions.data }
default:
return state
}
}
store.js
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
引入
import { Provider } from "react-redux"
import store from "./redux/index"
ReactDOM.render(
<Provider store={ store } >
<App/>
</Provider>,
document.getElementById('root')
);
使用
// 在组件内 引入
import * as React from "react"
import { connect } from "react-redux"
import { changeUserInfo } from "@/redux/actions"
class Hello extends React.Component{
// 使用方式
// this.props.userInfo
// this.props.changeUserInfo( data )
...
// 省略
}
const mapStateToProps = ( state ) =>{
return {
userInfo: state.userInfo
}
}
const mapActionsToProps = ( dispatch )=>{
return {
changeUserInfo: ( data )=>{
dispatch( changeUserInfo( data ) )
}
}
}
export default connect( mapStateToProps, mapActionsToProps )( Hello )
作者:taoqun
地址:http://taoquns.com/paper/46
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。