Easy Peasy状态管理-如何正确获取和传递数据?

时间:2019-06-22 20:34:03

标签: javascript reactjs

我正在对React使用Easy Peasy状态管理。我想从一个商店位置创建多个Axios调用,并将其导入到需要显示正确数据的每个页面中。例如,我试图获取JSON占位符数据,并在组件内部使用该数据使用Hooks将其推送到状态。

但是出现以下错误:

model.js:14 Uncaught (in promise) TypeError: actions.setTodos is not a function
    at model.js:14

有人可以帮我吗?我在做什么错了?

我的商店代码(model.js):

import { thunk } from 'easy-peasy';

export default {
    todos: [],
    fetchTodos: thunk(async actions => {
        const res = await fetch(
            'https://jsonplaceholder.typicode.com/todos?_limit=10'
        );
        const todos = res.json();

        actions.setTodos(todos);
    }),
};

“我的页面”组件联系人:

import React, { useState, useEffect } from 'react';

import { useStoreActions } from 'easy-peasy';

import ReactHtmlParser from 'react-html-parser';

import { API_URL } from 'constants/import';

// import axios from 'axios';

const Contact = () => {
    const [contactPage, setContactPage] = useState([]);

    const { page_title, page_content, page_featured_image } = contactPage;

    const fetchTodos = useStoreActions(actions => actions.fetchTodos);

    useEffect(() => {
        fetchTodos();
    }, []);

    return (
        <section className="contact">
            <div className="page">
                <div className="row">
                    <div className="col-xs-12">
                        <h3 className="section__title">{page_title}</h3>
                        {ReactHtmlParser(page_content)}
                        {page_featured_image && (
                            <img src={API_URL + page_featured_image.path} />
                        )}
                    </div>
                </div>
            </div>
        </section>
    );
};

export default Contact;

1 个答案:

答案 0 :(得分:0)

你需要用行动。

import { action, thunk } from "easy-peasy";

export default {
    fetchTodos: thunk(async (actions, payload) => {
        const res = await fetch(
            "https://jsonplaceholder.typicode.com/todos?_limit=10"
        );
        const todos = res.json();

        actions.setTodos(todos);
    }),

    
    todos: [],
    setTodos: action((state, payload) => {
        console.log("---->>> payload!")
        state.todos = payload
    }),

};

我通常这样使用它,它非常适合我。