如何在非react组件之外的普通js文件内使用redux
·
组件中是如何使用redux
const store = createStore(todoApp, applyMiddleware(thunk))
ReactDOM.render((
<Provider store={store}>
<App/>
</Provider>
),
document.getElementById('root')
)
上面是使用redux入口必写的模板代码,再通过connect方法把容器组件和展示组件关联,使得在组件中使用redux十分的方便。但是突然说要在普通js文件中使用就有点闷逼了。其实一样的,只是是用的最原始的redux的使用方法.
普通js文件中使用
- 在你声明store的地方导出store
const store = createStore(todoApp, applyMiddleware(thunk))
ReactDOM.render((
<Provider store={store}>
<App/>
</Provider>
),
document.getElementById('root')
)
export {store} //导出store
- 在普通js文件中引入store,通过store的getState和dispatch 拿值更新值
import {store} from "../index";
import {addTodo} from "../redux/actions";
function normalJs (props) {
console.log('普通js文件');
console.log('store',store);
console.log('store.getState',store.getState());
store.dispatch(addTodo('通js文件aaaa'))
}
export {normalJs}
3.界面上调用测试
<button onClick={()=>{normalJs()}}>调用普通js文件中的方法</button>
4.结果
和你展示组件通过connect从容器组件中获取的action是一个效果
store下有这两个常用的方法
- dispatch 调用action更新数据
- getState 获取数据
最原始的redux是怎么用的
- 最原始既要自己监听,app入口直接把store当属性进行传递
/*index.js*/
const store=createStore(counter) //内部会第一次调用reducer函数获得初始state
ReactDOM.render((<App store={store}/>), document.getElementById('root'))
//订阅监听(store中的状态变化了,就会调用进行重绘)
store.subscribe(()=>{
ReactDOM.render((<App store={store}/>), document.getElementById('root'))
})
- 更新值,获取值
/*App.js*/
省略...
//更新值
addNum=()=>{
//调用Store的dispatch去更新状态
//action也没单独写,参数直接是原始的它要的对象
this.props.store.dispatch({type:'INCREMENT',data:1})
}
省略...
render() {
//拿值
//自己通过属性传递的store调用getState方法获取值
const count=this.props.store.getState()
}
这是最原始时候的用法了,把通过属性传递的store导出给普通js文件用不是一个道理吗,很长时间没用dispatch和getstate都差点忘记了这俩最基本的方法了。现在都是自动帮你dispatch和获取值。
更多推荐

所有评论(0)