手写Redux:实现React-redux
import React, { Component } from 'react';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
// 假设有一个reducer函数
function counter(state = { value: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 };
case 'DECREMENT':
return { value: state.value - 1 };
default:
return state;
}
}
// 创建一个Redux store
const store = createStore(counter);
// 连接组件到Redux store
const mapStateToProps = (state) => ({
count: state.value
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' })
});
class Counter extends Component {
render() {
return (
<div>
<p>Count: {this.props.count}</p>
<button onClick={this.props.increment}>Increment</button>
<button onClick={this.props.decrement}>Decrement</button>
</div>
);
}
}
const ConnectedCounter = connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
// 在App组件中使用Provider来包裹ConnectedCounter
class App extends Component {
render() {
return (
<Provider store={store}>
<ConnectedCounter />
</Provider>
);
}
}
export default App;
这段代码展示了如何在一个React应用中使用Redux。首先创建了一个简单的reducer函数,然后创建了一个store。接着使用connect
函数将React组件连接到Redux store,并定义了state到props的映射以及dispatch方法到props的映射。最后,在App组件中使用<Provider>
组件来包裹已连接的Counter
组件,使得Counter
组件可以从上下文中访问store。
评论已关闭