Redux Hooks
Redux Hooks
在函数式组件中如果希望使用
useSelector
const result : any = useSelector(selector : Function, equalityFn? : Function)
当某个===
)来判断值的变化,而==
)来判断是否需要进行重渲染。在
import React from "react";
import { useSelector } from "react-redux";
export const CounterComponent = () => {
const counter = useSelector(state => state.counter);
return <div>{counter}</div>;
};
// 如果需要引用 Props 中的数据,则以闭包方式传入
export const TodoListItem = props => {
const todo = useSelector(state => state.todos[props.id]);
return <div>{todo.text}</div>;
};
在上述的用法中,每次组件渲染的时候都会创建新的
import React from "react";
import { useSelector } from "react-redux";
import { createSelector } from "reselect";
const selectNumOfDoneTodos = createSelector(
state => state.todos,
todos => todos.filter(todo => todo.isDone).length
);
export const DoneTodosCounter = () => {
const NumOfDoneTodos = useSelector(selectNumOfDoneTodos);
return <div>{NumOfDoneTodos}</div>;
};
export const App = () => {
return (
<>
<span>Number of done todos:</span>
<DoneTodosCounter />
</>
);
};
useDispatch
const dispatch = useDispatch();
该
import React from "react";
import { useDispatch } from "react-redux";
export const CounterComponent = ({ value }) => {
const dispatch = useDispatch();
return (
<div>
<span>{value}</span>
<button onClick={() => dispatch({ type: "increment-counter" })}>
Increment counter
</button>
</div>
);
};
当我们在父组件封装某个事件处理函数时,建议是使用
import React, { useCallback } from "react";
import { useDispatch } from "react-redux";
export const CounterComponent = ({ value }) => {
const dispatch = useDispatch();
const incrementCounter = useCallback(
() => dispatch({ type: "increment-counter" }),
[dispatch]
);
return (
<div>
<span>{value}</span>
<MyIncrementButton onIncrement={incrementCounter} />
</div>
);
};
export const MyIncrementButton = React.memo(({ onIncrement }) => (
<button onClick={onIncrement}>Increment counter</button>
));
useStore
const store = useStore();
该
import React from "react";
import { useStore } from "react-redux";
export const CounterComponent = ({ value }) => {
const store = useStore();
// EXAMPLE ONLY! Do not do this in a real app.
// The component will not automatically update if the store state changes
return <div>{store.getState()}</div>;
};