gatsby-node.js createPages is not sending data to component in pageContext

大憨熊 提交于 2019-12-11 06:03:33

问题


You can see I'm logging the data returned from my lambda function. The data is definitely coming back as expected. However, in the createPage(...), the allMessages in pageContext in the dashboard.js component is always null/undefined.

Why?...

dashboard.js

const DashboardPage = ({ pageContext: { allMessages } }) => (
    <Layout>
        <SEO title="Dashboard" keywords={[`gatsby`, `application`, `react`]} />
        <h1>Dashboard</h1>
        <p>Welcome to your new Gatsby site.</p>
        {console.log('allMessages: ', allMessages)}
        {allMessages.map(mssg => (
            <li
                key={mssg.id}
                style={{
                    textAlign: 'center',
                    listStyle: 'none',
                    display: 'inline-block'
                }}
            >
                <Link to={`/message/${mssg.name}`}>
                    <p>{mssg.name}</p>
                </Link>
            </li>
        ))}
    </Layout>
);

export default DashboardPage;

gatsby-node.js

exports.createPages = async ({ actions: { createPage } }) => {
    get('get-messages')
        .then(allMessages => {
            console.log('gatsby-node allMessages: ', allMessages);
            // Create a page that lists all Pokémon.
            createPage({
                path: `/dashoard`,
                component: require.resolve('./src/pages/dashboard.js'),
                context: { allMessages }
            });
        })
        .catch(err => {
            return Promise.reject(new Error(err));
        });
};

I'm blocked. Thank you for sharing your expertise!

EDIT:

This doesn't work either. Same undefined in dashboard.js...

exports.createPages = async ({ actions: { createPage } }) => {
    get('get-messages')
        .then(allMessages => {
            // allMessages = typeof allMessages === 'string' ? JSON.parse(allMessages) : allMessages;
            // console.log('gatsby-node allMessages: ', allMessages);
            // // Create a page that lists all Pokémon.
            const test = [{ name: 'Test message' }];
            createPage({
                path: `/dashoard`,
                component: require.resolve('./src/pages/dashboard.js'),
                context: { allMessages: test }
            });
        })
        .catch(err => {
            return Promise.reject(new Error(err));
        });
};

回答1:


The context data you're passing in CreatePages is already accessible in your DashboardPage component as a prop.
Instead of trying to take it into your DashboardPage component as a parameter, try accessing the allMessages data directly with this.props.pageContext.



来源:https://stackoverflow.com/questions/53990208/gatsby-node-js-createpages-is-not-sending-data-to-component-in-pagecontext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!