React redux 获取数据store.getState()

一、获取数据store.getState()
在这里插入图片描述
src/store/index.js

import { createStore } from 'redux'  //  引入方法
import reducer from './reducer'    
const store = createStore(reducer) // 创建数据存储仓库
export default store   

src/store/reducer.js

const defaultState = {
    inputValue : 'hello world'
}
function fn(state = defaultState,action){
        return state
}
const state=fn
export default state

组件使用:
src/views/a.js

import React from 'react'
import store from '../store/index' 
class A extends React.Component {
constructor(props){ 
  super(props)
  this.state=store.getState();
}
render() {
    return (
      <div >
          a页面
		{this.state.inputValue}
      </div >
    )
  }
}
export default A

二、修改数据 store.dispatch(action)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的 Redux Demo,它包括一个计数器组件和一个 Redux store: 1. 安装 Redux:在项目中使用 npm 或 yarn 安装 Redux。 `npm install redux` 2. 创建 store:使用 createStore() 方法创建一个 store,并将 reducer 作为参数传递给它。 ``` import { createStore } from 'redux'; // 定义 reducer const counterReducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } // 创建 store const store = createStore(counterReducer); ``` 3. 定义 reducer:reducer 是一个纯函数,接收当前状态和 action,返回新状态。它必须是纯函数,因为它不应该修改输入参数,也不应该有任何副作用。 4. 创建 action:action 是一个简单的对象,描述应用程序中发生的事件。它必须包含一个 type 属性,指定要执行的操作类型。 ``` // 创建 action const incrementAction = { type: 'INCREMENT' }; const decrementAction = { type: 'DECREMENT' }; ``` 5. 分发 action:使用 store.dispatch() 方法将 action 分发到 reducer 中。 ``` // 分发 action store.dispatch(incrementAction); // state = 1 store.dispatch(incrementAction); // state = 2 store.dispatch(decrementAction); // state = 1 ``` 6. 访问状态:使用 store.getState() 方法访问 store 中的当前状态。 ``` // 访问状态 console.log(store.getState()); // 1 ``` 7. 监听变化:使用 store.subscribe() 方法监听 store 中状态的变化,并在状态发生变化时执行相应的操作。 ``` // 监听变化 store.subscribe(() => console.log(store.getState())); ``` 完整代码如下: ``` import { createStore } from 'redux'; // 定义 reducer const counterReducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } } // 创建 store const store = createStore(counterReducer); // 创建 action const incrementAction = { type: 'INCREMENT' }; const decrementAction = { type: 'DECREMENT' }; // 分发 action store.dispatch(incrementAction); // state = 1 store.dispatch(incrementAction); // state = 2 store.dispatch(decrementAction); // state = 1 // 访问状态 console.log(store.getState()); // 1 // 监听变化 store.subscribe(() => console.log(store.getState())); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值