初次接触react-redux
,写下来总是感觉有点繁琐。有什么办法能够简化吗?
使用过程: index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './redux/store'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
store.js
本来视频课程里面的store
被抽成了好几个js
文件,
我觉得麻烦就合并在了一起,合并跟拆开有什么差别,大佬还请告知。
import {createStore, applyMiddleware} from 'redux'
// 用于支持异步action
import thunk from 'redux-thunk'
const states = {
INCREMENT: 'increment',// 增加
DECREMENT: 'decrement',// 减少
}
const refucers = (state = 0, action) => {
const {type, data} = action
switch (type) {
case states.INCREMENT:
return state + data
case states.DECREMENT:
return state - data
default:
return state
}
}
export const mutations = {
INCREMENTACTION: data => ({type: states.INCREMENT, data}),
DECREMENTACTION: data => ({type: states.DECREMENT, data}),
}
export const actions = {
INCREMENTACTIONASYNC: (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(mutations.INCREMENTACTION(data))
}, time);
}
}
}
// 这是单独抽出来的文件内容, 在调用里面会用到
// // 同步action, action的值为object类型的一般对象
// export const INCREMENTACTION = data => ({type: INCREMENT, data})
// export const DECREMENTACTION = data => ({type: DECREMENT, data})
// export const ADD_PERSONACTION = data => ({type: ADD_PERSON, data})
// // 异步action, action的值为函数
// export const INCREMENTACTIONASYNC = (data, time) => {
// return (dispatch) => {
// setTimeout(() => {
// dispatch(INCREMENTACTION(data))
// }, time);
// }
// }
export default createStore(refucers, applyMiddleware(thunk))
组件调用
import React, { Component } from 'react'
import { connect } from "react-redux";
import { mutations } from "../../redux/store";
// 跟上面的分别暴露调用相关代码
// import { INCREMENTACTION, DECREMENTACTION, INCREMENTACTIONASYNC } from "../../redux/store";
class CountUI extends Component {
increment = () => {
const { value } = this.selectNumber
this.props.increments(value*1)
}
decrement = () => {
const { value } = this.selectNumber
this.props.decrements(value*1)
}
render() {
console.log(this.props);
return (
<div>
<h1>value: {this.props.count}</h1>
<select ref={c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
// 1. 映射状态
// 2. 映射操作状态的方法
export default connect(
state => ({count: state}),
{
increments: mutations.INCREMENTACTION,
decrements:mutations.DECREMENTACTION,
},
// { 这种是比较期待的书写形式, 而不是上面那种,如果不想要上面那种引用,又要下面这种格式,就又需要结构赋值一遍
// INCREMENTACTION,
// DECREMENTACTION,
// INCREMENTACTIONASYNC
// }
)(CountUI)
怎样才能更优化简洁一点呢, vuex
的书写个人还是蛮喜欢的。
没有区别,看你喜欢
Redux 的特点就是大量的模板代码(或者说他的理念就是用这种设计来明确数据修改流向和强制 immutable),如果你不喜欢的话可以考虑换一个库做状态管理..