【问题标题】:Easy-peasy useStoreActions not updating state immediately?Easy-peasy useStoreActions 不会立即更新状态?
【发布时间】:2020-06-14 03:59:49
【问题描述】:

让我们说这是我的代码

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

【问题讨论】:

  • 我的回答对内森有帮助吗?你找到解决办法了吗?

标签: javascript reactjs react-native redux easy-peasy


【解决方案1】:

easy-peasy initialState 中是一个不可变的值,用于初始化您的商店。所以你的setDonation 函数不能改变这个值。

此处显示了您想要做什么的完整示例(尽管是人为的!),其中 cmets 应该解释发生了什么:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-07
    • 2018-08-05
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多