React-Redux是什么?

React-Redux是什么?

React-Redux是Redux的官方React绑定库,用于连接React和Redux的。它能够使你的React组件从Redux store中读取数据,并且向store分发actions以更新数据。

为什么使用React-redux

使用React-redux可以使redux部分代码更简洁更明了,比如组建中需要使用到的数据都在mapStateToProps方法中,组建中需要修改store的操作都在mapDispatchToProps中。

如何使用React-redux

下面是一个简单的例子

//store/index.js 
//store部分的代码和没有使用react-redux时相同
import { createStore } from 'redux'
import reducer from './reducer';
const store = createStore(reducer);
 
export default store;
//reducer.js
//reducer部分和未使用react-redux时相同
const defaultState = {
inputValue: '',
list: []
}
//reducer 可以接受state但是不能修改state,需要对state进行深拷贝
export default (state = defaultState, action) => {
if (action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState
}
if (action.type === 'add_input_value') {
const newState = JSON.parse(JSON.stringify(state));
newState.list = [...state.list, state.inputValue]
newState.inputValue = '';
return newState;
}
return state;
}
//index.js
//入口需要稍微调整
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
import { Provider } from 'react-redux';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<TodoList />
</Provider>,
document.getElementById('root')
);
import React, { Component, Fragment } from 'react';
import { connect } from 'react-redux';
class TodoList extends Component {
constructor(props){
super(props)
this.handleList = this.handleList.bind(this);
}
handleList(){
return this.props.list.map((item) => {
return <li>{item}</li>
})
}
render() {
return (
<Fragment>
<div>
<input 
value = {this.props.inputValue} 
onChange = {this.props.handleInputChange}
/>
<button onClick={this.props.btnClick}>提交</button>
</div>
<ul>
{this.handleList()}
</ul>
</Fragment>
);
}
}
function mapStateToProps(state) {
return {
inputValue: state.inputValue,
list: state.list
}
}
function mapDispatchToProps(dispatch) {
return {
handleInputChange:function(e){
const action = {
type: 'change_input_value',
value: e.target.value
}
dispatch(action);
},
btnClick:function(){
const action = {
type: 'add_input_value'
}
dispatch(action);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

更多web前端知识,请查阅 HTML中文网 !!

以上就是React-Redux是什么?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » React 答疑