Redux 是一个广泛使用的 JavaScript 状态管理库,它可以帮助开发者更好地组织和管理应用的状态。在 React 应用中,Redux 通常与
react-redux
库一起使用。本篇文章将通过5个小例子,帮助你轻松入门和实践 React Redux。
1. 理解 Redux 的核心概念
在开始之前,我们需要了解 Redux 的三个核心概念:
store
、
action
和
reducer
。
Store
:Redux 应用中存储所有状态的对象。
Action
:一个描述“发生了什么”的对象,由
action creators
创建。
Reducer
:一个纯函数,用于根据当前的 state 和 action 计算新的 state。
2. 小例子一:计数器应用
2.1 创建 Store
import { createStore } from ‘redux’;
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case ‘INCREMENT’:
return { count: state.count + 1 };
case ‘DECREMENT’:
return { count: state.count – 1 };
default:
return state;
}
}
const store = createStore(counterReducer);
2.2 创建 Action Creators
function increment() {
return { type: ‘INCREMENT’ };
}
function decrement() {
return { type: ‘DECREMENT’ };
}
2.3 连接 React 组件到 Store
import React from ‘react’;
import { connect } from ‘react-redux’;
function Counter({ count, increment, decrement }) {
return (
Count: {count}
);
}
const mapStateToProps = (state) => ({
count: state.count
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch(increment()),
decrement: () => dispatch(decrement())
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
3. 小例子二:Todo 列表应用
3.1 创建 Store
import { createStore } from ‘redux’;
const initialState = {
todos: []
};
function todoReducer(state = initialState, action) {
switch (action.type) {
case ‘ADD_TODO’:
return {
…state,
todos: […state.todos, action.payload]
};
default:
return state;
}
}
const store = createStore(todoReducer);
3.2 创建 Action Creators
function addTodo(text) {
return { type: ‘ADD_TODO’, payload: text };
}
3.3 连接 React 组件到 Store
import React from ‘react’;
import { connect } from ‘react-redux’;
function TodoList({ todos, addTodo }) {
return (
-
{todos.map((todo, index) => (
- {todo}
))}
);
}
const mapStateToProps = (state) => ({
todos: state.todos
});
const mapDispatchToProps = (dispatch) => ({
addTodo: (text) => dispatch(addTodo(text))
});
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
4. 小例子三:天气应用
4.1 创建 Store
import { createStore } from ‘redux’;
const initialState = {
city: ”,
weather: ”
};
function weatherReducer(state = initialState, action) {
switch (action.type) {
case ‘SET_CITY’:
return {
…state,
city: action.payload
};
case ‘FETCH_WEATHER’:
return {
…state,
weather: action.payload
};
default:
return state;
}
}
const store = createStore(weatherReducer);
4.2 创建 Action Creators
function setCity(city) {
return { type: ‘SET_CITY’, payload: city };
}
function fetchWeather(city) {
return (dispatch) => {
// Fetch weather data from an API
// dispatch({ type: ‘FETCH_WEATHER’, payload: weatherData });
};
}
4.3 连接 React 组件到 Store
”`javascript
import React from ‘react’;
import { connect } from ‘react-redux’;
function WeatherApp({ city, weather, setCity, fetchWeather }) {
return (
value={city