Ошибка компонента метода рендеринга - неверный вызов ловушки. Хуки могут быть вызваны только внутри тела компонента функции - PullRequest
0 голосов
/ 24 апреля 2020

У меня возникла проблема с правильным отображением данных в базовом c компоненте?

questionThree. js

    import React, {Component} from 'react';
    import { makeStyles } from '@material-ui/core/styles';
    import List from '@material-ui/core/List';

    import Paper from '@material-ui/core/Paper';

    import Android from "@material-ui/icons/Android";
    import Pets from "@material-ui/icons/Pets";
    import BugReport from "@material-ui/icons/BugReport";

    import QuestionListItem from './questionListItem';
    import { createRowData } from './mocks';

    const createMockData = () =>{
        /* Please do not refactor this function */
        return [
            createRowData({species: 'Robot', name: 'T-100', Icon: Android, description: "Likes long walks, walking over the bones of it's enemies"}),
            createRowData({species: 'Bug', name:'Barry', Icon: BugReport, description: "Likes long walks, and creating problems in all your code"}),
            createRowData({species: 'Rabbit', name:'Roger', Icon: Pets, description: "Likes long walks and getting to know the inner you"}),
            createRowData({species: null, name: null, Icon: null, description: null}),
        ]
    };

    const useStyles = makeStyles(() => ({
        container:{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
        },
        root: {
            width: '100%',
        },
        inline: {
            display: 'inline',
        },
    }));

    class questionThree extends Component {
        render(){
            const classes = useStyles();
            const mockData = createMockData();
            return (
                <div className={classes.container}>
                    <Paper>
                        <List className={classes.root}>
                            {mockData.map((item, i) =>{
                                return <QuestionListItem item={item} key={item.id} divider={i !== mockData.length -1}/>
                            })}
                        </List>
                    </Paper>
                </div>
            );
        }
    }
    export default questionThree

*question.js*

import React from 'react'
import Typography from "@material-ui/core/Typography";
import Solution from './images/solution.png'
import { CardMedia } from '@material-ui/core';
const question = ()=>{
    return (
        <div>
            <Typography variant="h4" gutterBottom>
                Question Three
            </Typography>
            <Typography variant="h5" gutterBottom>
                List on the fritz
            </Typography>
            <Typography variant="body1" gutterBottom>
                This task revolves around a bug in the render method of a basic component.
            </Typography>
            <Typography variant="body1" gutterBottom>
                Your task if you choose to accept it, is to resolve this bug (displayed on the right and in the console) .
            </Typography>
            <Typography variant="body1" gutterBottom>
                As with all the questions in this tech test, you may or may not wish to refactor some of the code.
            </Typography>
            <Typography variant="h6" gutterBottom>
                Below is what the final solution should look like. (GUID'S will vary)
            </Typography>
            <CardMedia
                image={Solution}
                style={{
                    width: '100%',
                    height: 500,
                    backgroundSize: 'contain',
                }}
                title="The Solution"
            />
        </div>
    )
};

export default  question

index . js

import React from 'react';
import QuestionThree from './questionThree';
import Question from './question'
import ErrorBoundary from '../../components/errorBoundary'
const questionThree = () =>{
    return (
        <ErrorBoundary question={Question}>
            <QuestionThree/>
        </ErrorBoundary>
    )
}

export default questionThree;

Я испробовал ряд решений и большинство решений, доступных в Google, и, похоже, ничего не работает. Я попробовал решение, предоставленное на https://reactjs.org/warnings/invalid-hook-call-warning.html, однако столкнулся с проблемой получения результатов из второго шага инструкции.

Чего мне не хватает? Это момент «Я должен был пойти к Спецсаверам»?

1 Ответ

0 голосов
/ 24 апреля 2020

makeStyles возвращает хук с именем useStyles, который можно вызывать только внутри функционального компонента. Вот почему вы получаете сообщение об ошибке.

В вашем случае измените questionThree на функциональный компонент

const questionThree = (props) =>  {
   const classes = useStyles();
   const mockData = createMockData();
   return (
            <div className={classes.container}>
                <Paper>
                    <List className={classes.root}>
                        {mockData.map((item, i) =>{
                            return <QuestionListItem item={item} key={item.id} divider={i !== mockData.length -1}/>
                        })}
                    </List>
                </Paper>
            </div>
        );
}
export default questionThree

Чтобы использовать его для компонентов класса, используйте withStyles HOC

import { withStyles } from '@material-ui/core/styles';

   const styles = {
        container:{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: '100%',
        },
        root: {
            width: '100%',
        },
        inline: {
            display: 'inline',
        },
   }
   class questionThree extends Component {
        render(){
            const {classes} = props
            const mockData = createMockData();
            return (
                <div className={classes.container}>
                    <Paper>
                        <List className={classes.root}>
                            {mockData.map((item, i) =>{
                                return <QuestionListItem item={item} key={item.id} divider={i !== mockData.length -1}/>
                            })}
                        </List>
                    </Paper>
                </div>
            );
        }
    }
    export default withStyles(styles)(questionThree);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...