Использование контекста для извлечения из магазина на странице React в следующем - PullRequest
1 голос
/ 26 апреля 2020

Я не уверен, правильно ли я сформулировал название для того, что я пытаюсь сделать? Новое в React, и я также использую Next js.

Я пытаюсь получить данные из своих фиктивных данных из сохраненных сообщений чата, и я получаю эту ошибку:

    ×
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
ChatBox
./pages/chat.js:11
   8 | const ChatBox = () => {
   9 |   const [textValue, changeTextValue] = React.useState('');
  10 | 
> 11 |   const [allChats] = React.useContext(CTX)
  12 | 
  13 |   console.log(allChats);
  14 |   return (

Не уверен, в чем проблема, и что я могу вытащить в контексте, я, вероятно, упускаю что-то действительно простое или, может быть, что-то связанное со следующим js?

Здесь я поделюсь своим магазином и файлом, который пытаюсь использовать, чтобы получить контекст

Store. js:

    mport React from 'react'

export const CTX = React.createContext();

const initState = {
    general: [
        { from: 'user1', msg: 'hello' },
        { from: 'user2', msg: 'u stink' },
        { from: 'user3', msg: 'some other words' }
    ],
    channel2: [
        { from: 'user1', msg: 'hello' }
    ]
}
const reducer = (state, action) => {
    const { from, msg, topic } = action.payload;
    switch (action.type) {
        case 'RECEIVE_MESSAGE':
            return {
                ...state,
                [topic]: [
                    ...state[topic],
                    { from, msg }
                ]
            }
        default:
            return state
    }
}

export const Store = (props) => {

    const reducerHook = React.useReducer(reducer, initState)

    return (
        <CTX.Provider value={reducerHook}>
            {props.children}
        </CTX.Provider>
    )
}

ChatBox. js -

    import React from "react";
import styled from "styled-components";
import Sidebar from "../components/Sidebar";
import UserMessage from "../components/UserMessage";
import { Store, CTX } from '../components/Store'


const ChatBox = () => {
  const [textValue, changeTextValue] = React.useState('');

  const [allChats] = React.useContext(CTX);

  console.log(allChats);
  return (

    <Layout>
      <Store>
        <Sidebar />
        <Wrapper>

          <InnerBoxWrapper>

            <InnerBox>
              <UserMessage />
              <input label="Send a chat" value={textValue} onChange={e => changeTextValue(e.target.value)} type="text" />
            </InnerBox>

          </InnerBoxWrapper>
          <h1>test</h1>
        </Wrapper>
      </Store>
    </Layout>
  )
}

1 Ответ

2 голосов
/ 26 апреля 2020

Вы визуализируете Store внутри ChatBox компонента. Чтобы использовать контекст, вам нужно отобразить компонент ChatBox как дочерний компонент компонента Store.

Итак, удалите Store из компонента ChatBox и оберните ChatBox с помощью Store во время экспорта.

import React from "react";
import styled from "styled-components";
import Sidebar from "../components/Sidebar";
import UserMessage from "../components/UserMessage";
import { Store, CTX } from '../components/Store'


const ChatBox = (props) => {
    const [textValue, changeTextValue] = React.useState('');

    const [allChats] = React.useContext(CTX);

    console.log(allChats);
    return (

        <Layout>
            {/*<Store>*/}
                <Sidebar />
                <Wrapper>

                    <InnerBoxWrapper>

                        <InnerBox>
                            <UserMessage />
                            <input label="Send a chat" value={textValue} onChange={e => changeTextValue(e.target.value)} type="text" />
                        </InnerBox>

                    </InnerBoxWrapper>
                    <h1>test</h1>
                </Wrapper>
            {/*</Store>*/}
        </Layout>
    )
};

export default (props) => <Store><ChatBox {...props}/></Store>
...