Неисправность «Пользователь не определен» при фильтрации и отображении результатов поиска с помощью React.Js / Material-Ui - PullRequest
0 голосов
/ 27 ноября 2018

Я пытаюсь создать панель поиска, которая фильтрует массив пользователей, помещенных в сетку, используя стиль Material-Ui.Я несколько раз пытался отобразить и отобразить пользователей, но не могу отобразить страницу с пользователями, отображаемыми в сетке.

Я получаю сообщение об ошибке «Пользователь не определен»

Вот код UserList.js

// implemented a class based component
import React, { Component } from 'react';
import './UserList.css'
// we will be using this for our cards
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import * as contentful from 'contentful';

class UserList extends Component {
  // state object contains two properties
    state = {
      users: [
              {
                "id": 1,
                "name": "Mary Ann",
                "socialmedia": "Instagram",
                "following": "401k"
              },
              {
                "id": 2,
                "name": "Jessica P",
                "socialmedia": "Instagram",
                "following": "600k"
              }
            ],
      searchString: ''
    }

  constructor() {
    // super is the parent consturctor
    super()
    // we are making sure the list is loaded at the beginning of the lifecycle
    this.getUsers()
  }
// here we are implementing that method after we retreived it above
 getUsers = () => {
   // client.getEntries
   ({
     // what data are we returning
     content_type: 'user',
     // we use query because we will have a search filter activated
     // with this we will also need to make sure whent he user searches, the search barupdates accordingly
     query: this.state.searchString
   })
   // returns a promise
   // once there is a response, we use that callback function to make sure we ae setting the state again
   .then((response) => {
     this.setState({users: response.elements})
   })
   // in case there is an error we want to catch it
   .catch((error) => {
     console.log("Error occured while fetching data")
     console.log(error)
   })
 }
 // we are passing an event as a parameter
onSearchInputChange = (event) => {
  // if the value entered by the user in the textfield, make sure the state is updated
  if (event.target.value) {
    this.setState({searchString: event.target.value})
    // if that is not the case,we set the state to an empty string
  } else {
     this.setState({searchString: ''})
  }
  // we are making sure so the query is executed again and we are making sure only the users are returned, matching to our search stirng
  this.getUsers()
}
// The View
// now we are making sure it is rendered in the browser
 render() {
   return (
     <div>
      {this.state.users ? (
           <div>
              <TextField style={{padding: 24}}
                id="searchInput"
                placeholder="Search for Influencers"
                margin="normal"
                onChange = {this.onSearchInputChange} />
        <Grid container spacing={24} style={{padding: 24}}>
        { this.state.users.map(currentUser => (
                                <Grid item xs={12} sm={6} lg={4} xl={3}>
                                    <User user={currentUser} />
                                </Grid>
                            ))}
                        </Grid>
                    </div>
                ) : "No courses found" }
            </div>
        )
    }
}

export default UserList;

Вот код User.js

import React from 'react';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia '
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/button';

const User = (props) => {
     return (
      <div>
         <h1 className='profile'> #HASHTAG HOUND </h1>
         {this.state.users.map((element, index) => {
           return  <div>
           <h1 className='profile'>{element.name}</h1>
           <h2 className='profile'>{element.socialmedia}</h2>
            <h2 className='profile'>{element.following}</h2>
           </div>
         })}
      </div>
    )
  }
}

export default User;

Ответы [ 2 ]

0 голосов
/ 27 ноября 2018

Проблема решена.Нажмите здесь, чтобы посмотреть => WORKING DEMO

Вы пытались получить данные пользователей из файла UsersList, который невозможно импортировать, необходимо создатьдругой файл, в который вы помещаете данные и используете данные в обоих файлах, экспортируя данные из файла и просто импортируя const user из этого файла usersListData.jsx, как показано в рабочей демонстрации, и применяете карту наэто const.

0 голосов
/ 27 ноября 2018

Похоже, проблема в том, что User Компонент не импортируется в файл UserList.js.Просто импортируйте его: import User from './User'; (установите правильный путь).

...