UI组件和容器组件
UI组件:只负责页面渲染,没有或极少有逻辑处理
容器组件:负责页面逻辑,将UI组件作为子组件集成进来
无状态组件:是一个函数,将只有render
函数的UI组件简化成无状态组件,可提高性能
redux-thunk中间件
安装:npm install redux-thunk --save
在store/index.js中进行使用
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const store = createStore(reducer, applyMiddleware(thunk))
export default store
使用了redux-thunk后,会对dispatch方法进行升级,action可以是一个函数
进而将Ajax异步逻辑拆分出来,放到action中进行操作,而redux-saga是拆分到一个新文件中进行管理
①当action是一个对象时,通过store的dispatch方法会直接把action传到store,在传给reducer
②当action是一个函数时,通过store的dispatch方法会执行这个函数,并将dispatch方法作为参数传递进去
//声明
const getInitAction = (list) => ({
type: INIT_LIST,
list
})
export const getAjaxAction = () => {
return (dispatch) => {
axios.get('/api/list.json').then((res) => {
const list = res.data.list
const action = getInitAction(list)
dispatch(action)
})
}
}
//调用
componentDidMount() {
const action = getAjaxAction()
store.dispatch(action)
}
react-redux
安装:npm install react-redux --save
作用:方便在react使用redux
①在入口文件中引入Provider提供器,绑定store,即可将store提供给所有子组件
import TodoListRR from './TodoListRR'
import { Provider } from 'react-redux'
import store from './storeRR'
const App = (
<Provider store={store}>
<TodoListRR />
</Provider>
)
ReactDOM.render(App, document.getElementById('root'));
②在组件中,用react-redux提供的connect方法将store和组件关联起来
<input value={this.props.inputValue} onChange={this.props.handleInputChange} />
const mapStateToProps = (state) => {
return {
inputValue: state.inputValue
}
}
const mapDispatchToProps = (dispatch) => {
return {
handleInputChange(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
dispatch(action)
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoListRR)
//connet方法将数据mapStateToProps、逻辑mapDispatchToProps和UI组件TodoListRR结合成容器组件