简单易用的 useStoreActions 不立即更新状态?

Easy-peasy useStoreActions not updating state immediately?

假设这是我的代码

  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 它没有显示新的捐赠数据

In 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"));

你会发现这个工作 here