javascript - Easy-peasy useStoreActions 不会立即更新状态?
问题描述
可以说这是我的代码
const donation = useStoreState(
state => state.user.initialState.donationData,
)
const setDonation = useStoreActions(
actions => actions.donation.setDonation,
)
setDonation({
amount: 1000000,
message: 'donation from easy peasy',
payment_method_id: '1',
receiver_id: '1',
})
console.log('donation', donation)
当我试图 console.log 它没有显示新的捐赠数据
解决方案
在easy-peasy initialState
中是一个不可变的值,用于初始化您的商店。因此,您的setDonation
函数将无法更改此值。
此处显示了您想要做什么的完整(尽管是人为的!)示例,其中的注释应该解释发生了什么:
import React, { Component } from "react";
import { render } from "react-dom";
import {
useStoreState,
action,
createStore,
StoreProvider,
useStoreActions
} from "easy-peasy";
// Define your model
const donationModel = {
donation: {},
setDonation: action((state, payload) => {
state.donation = payload;
})
};
// Define you application store
const storeModel = {
donations: donationModel
};
// Create an instance of the store
const store = createStore(storeModel);
const App = () => (
// Wrap the Donation component with the StoreProvider so that it can access the store
<StoreProvider store={store}>
<Donation />
</StoreProvider>
);
const Donation = () => {
// Dispatch a setDonation action to add donation data to the store
useStoreActions(actions =>
actions.donations.setDonation({
amount: 1000000,
message: "donation from easy peasy",
payment_method_id: "1",
receiver_id: "1"
})
);
// Retrieve data from the store using useStoreState
const donationMessage = useStoreState(
state => state.donations.donation.message
);
// Display the donation message returned from the store!
return <>{donationMessage}</>;
};
render(<App />, document.getElementById("root"));
你可以在这里找到这个工作。
推荐阅读
- excel - 将excel中的百分比值限制在0%到100%之间
- android - 如何在 TextView (Android) 中启用垂直自动滚动
- python - 如何确定卫星是否进行了机动?
- solr - 是否可以保护 Apache Solr 8.5.1 仪表板页面而不是查询页面?
- python - 从网站获取名称时出现错误
- python - 如何在 Flask 中为 http 调用提供值列表?
- python-3.x - 从阿拉伯语文本输出的空 WordCloud PNG
- selenium - java.io.IOException: Stream closed at runner.testrunner.tearDownClass - 尝试使用 Cucumber 和 TestNG 并行执行
- ip - 如何在 192.168.0.0/16 上执行 IP 子网划分?
- php - 通过 php 中的 htaccess 从 url 替换 ?id= 和 .php