Easy-peasy useStoreActions 没有立即更新状态?

Nat*_*die 6 javascript reactjs react-native redux easy-peasy

可以说这是我的代码

  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)
Run Code Online (Sandbox Code Playgroud)

当我尝试 console.log 时,它没有显示新的捐赠数据

Ben*_*ith 4

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"));
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到这个工作。