redux
作者:互联网
store 文件夹下:
index.js 文件
import reducer from './reducer' import { createStore } from 'redux'const store=createStore(reducer)
export default store reducer.js 文件 //定义一个默认状态 const defaultState={ msg:'你好世界' }
//导出一个函数 export default (state=defaultState,action)=> { let newState=JSON.parse(JSON.stringify(state)) switch(action.type){ case 'changeMsg': newState.msg=action.value break; default: break; }
return newState } // 使用 import {connect} from 'react-redux'
function App(props) {
return ( <> <div>redux: {props.msg}</div> <button onClick={props.changeMsg}> 点击修改redux</button> </> ) }
const mapStateToProps=(state)=>{ return { msg:state.msg } }
const mapDispatchToProps=(dispatch)=>{ return{ changeMsg(){ const action ={type:'changeMsg',value:'hello world'} dispatch(action) } } }
export default connect(mapStateToProps,mapDispatchToProps)(App)
//重要 在主入口文件中挂载 import {Provider} from 'react-redux' import store from './store' const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );
标签:const,action,msg,import,redux,store 来源: https://www.cnblogs.com/daxiong182/p/16268532.html