【发布时间】:2021-06-17 18:20:26
【问题描述】:
我在 redux 中有 2 个操作(都是异步的),我通过 dispatch 在我的功能组件中调用它们;第一个使用useEffect,第二个通过按钮单击。我想要做的是调度操作以从异步函数中检索它们,然后通过useState 在我的组件中使用它们。但是使用useState 不会渲染。
这是我的组件:
export default function Hello()
{
const { first, second } = useSelector(state => state.myReducer);
const dispatch = useDispatch();
const fetchFirst = async () => dispatch(getFirst());
const fetchSecond = async () => dispatch(getSecond());
const fetchFixturesForDate = (date: Date) => dispatch(getFixturesForDate(date));
const [superValue, setSuperValue] = useState('value not set');
useEffect(() => {
const fetch = async () => {
fetchFirst();
setSuperValue(first);
};
fetch();
}, []);
const getSecondOnClickHandler = async () =>
{
console.log('a')
await fetchSecond();
setSuperValue(second);
}
return (
<div>
<p>The super value should first display the value "first item" once retrieved, then display "second value" once you click the button and the value is retrieved</p>
<p>Super Value: {superValue}</p>
<p>First Value: {first}</p>
<p>Second Value: {second}</p>
<button onClick={async () => await getSecondOnClickHandler()}>Get Second</button>
</div>
)
}
superValue 永远不会呈现,即使我正在设置它,尽管来自 first 和 second 的值被检索并显示。
有什么帮助吗?
【问题讨论】:
标签: reactjs redux react-hooks