• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

React-Redux是什么?

react 搞代码 4年前 (2021-12-28) 17次浏览 已收录 0个评论

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);

更多react的相关知识,请查阅 搞代码网 !!

以上就是React-Re来源gaodai$ma#com搞$代*码网dux是什么?的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:React-Redux是什么?

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址