React变量管理与传递使用场景
大约 2 分钟
React变量管理与传递使用场景
State
State + Reducer
reducer:(state,action)->state函数是一个接收state、action变成新的state的函数。 也就是说界面中,调用提供的dispatch(action),得到新的状态。
function tasksReducer(tasks, action) {
switch (action.type) {
case 'added': {
return [
...tasks,
{
id: action.id,
text: action.text,
done: false,
},
];
}
case 'changed': {
return tasks.map((t) => {
if (t.id === action.task.id) {
return action.task;
} else {
return t;
}
});
}
case 'deleted': {
return tasks.filter((t) => t.id !== action.id);
}
default: {
throw Error('未知 action: ' + action.type);
}
}
}
import { useReducer } from 'react';
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
let nextId = 3;
const initialTasks = [
{id: 0, text: '参观卡夫卡博物馆', done: true},
{id: 1, text: '看木偶戏', done: false},
{id: 2, text: '打卡列侬墙', done: false}
];
export default function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
function handleAddTask(text) {
dispatch({
type: 'added',
id: nextId++,
text: text,
});
}
function handleChangeTask(task) {
dispatch({
type: 'changed',
task: task,
});
}
function handleDeleteTask(taskId) {
dispatch({
type: 'deleted',
id: taskId,
});
}
return (
<>
<h1>布拉格的行程安排</h1>
<AddTask onAddTask={handleAddTask} />
<TaskList
tasks={tasks}
onChangeTask={handleChangeTask}
onDeleteTask={handleDeleteTask}
/>
</>
);
}
Context
Context + Reducer
需要创建两个 Context,分别是 Context 和 DispatchContext,用于向下传递 reducer 管理的状态和 dispatch。
export const TasksContext = createContext(null);
export const TasksDispatchContext = createContext(null);
export default function TaskApp() {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
// ...
return (
<TasksContext.Provider value={tasks}>
<TasksDispatchContext.Provider value={dispatch}>
...
</TasksDispatchContext.Provider>
</TasksContext.Provider>
);
}
//使用:
const tasks = useContext(TasksContext);
const dispatch = useContext(TasksDispatchContext);
Ref
Effect
Effect 允许你指定由渲染自身,而不是特定事件引起的副作用。
在聊天中发送消息是一个“事件”,因为它直接由用户点击特定按钮引起。
建立服务器连接是一个 Effect,因为无论哪种交互致使组件出现,它都应该发生。
Effect 在提交结束后、页面更新后运行。此时是将 React 组件与外部系统(如网络或第三方库)同步的最佳时机。
管理全局性的状态:Valtio
显示:To access the data in this store, we'll use useSnapshot 更改: we simply mutate properties on the store we created, not the snap