简体   繁体   中英

Why onMouseOver doesn't work fine Reactjs

there is such a task

When hovering over a selected month, display a list of people who were born this month. Already tried without .bind but still have an error

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import './styles.css';
import classes from './components/Month/month.module.css'


function App() {
    // state = {
    //   users: false
    // }
    const [users, setUser] = useState(null);
    const usersVisible = false;

    const fetchData = async () => {
        const response = await axios.get(
            'https:api/task0/users'
        );

        setUser(response.data);
    };

    const groupedUsers = users && users.reduce((acc, n) => {


        acc[new Date(n.dob).getMonth()].users.push(n);
        return acc;

    }, [...Array(12)].map((n, i) => ({
        month: new Date(0, i).toLocaleString('ru-RU', { month: 'long' }),
        users: []



    }))
    );

    const onHover = () => {
        return usersVisible = true;
    }
    console.log(usersVisible);
    return (
        <div className="App">
            <h1>Users list</h1>


            {/* Fetch data from API */}
            <div>
                <button className="fetch-button" onClick={fetchData}>
                    download users
        </button>
                <br />
            </div>

            {/* Display data from API */}
            {}
            <div className="users">
                {groupedUsers && groupedUsers.map(n => (
                    <div id="months" key={n.month} className={n.users > 0 ? classes.month.grey : n.users > 2 ?
                        classes.blue : n.users > 6 ? classes.green : classes.red} onMouseOver={(event) => this.onHover.bind(event)}>
                        <h2>{n.month}</h2>
                        {n.users.map(user => (
                            usersVisible ?

                                <div key={user.id} >

                                    <div>
                                        <h4 className={classes.userId}>user #{user.id}</h4>
                                        данные пользователя...</div>
                                </div> : null
                        ))}
                    </div>
                ))}
            </div>

        </div>
    );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

Here is code of error

TypeError: Cannot read property 'onHover' of undefined
onMouseOver
C:/Users/Константин/Desktop/react/new-app/src/index.js:60
  57 |     <div className="users">
  58 |      {groupedUsers && groupedUsers.map(n => (
  59 | <div id="months" key={n.month}  className={n.users > 0 ? classes.month.grey  : n.users > 2 ? 
> 60 |       classes.blue : n.users > 6 ? classes.green : classes.red} onMouseOver={(event) => this.onHover.bind(event)}>
     | ^  61 |   <h2>{n.month}</h2>
  62 |   {n.users.map(user => (
  63 |     usersVisible ? 

the function onHover changes the value of the variable, which should lead to the output of the block in jsx. Where is the problem hiding? thanks a lot!!

Source of the error : As you are working on a function component, this keyword is not a reference to your component, but to the window. So in order to access, your onHover you just call it directly, not with the use of this or bind .

Also while this show/hide is relevant to a state that your component will have, usersVisible should be handled by state.

function App() {
  const [users, setUser] = useState(null);
  const [usersVisible, setVisibility] = useState(false);

  const fetchData = async () => {
    const response = await axios.get(
      'https://yalantis-react-school.herokuapp.com/api/task0/users'
    );

    setUser(response.data);
  };

  const groupedUsers = users && users.reduce((acc, n) => {
    acc[new Date(n.dob).getMonth()].users.push(n);
    return acc;
  }, [...Array(12)].map((n, i) => ({
    month: new Date(0, i).toLocaleString('ru-RU', { month: 'long' }),
    users: []
  })));

  return (
    <div className="App">
      <h1>Users list</h1>

      {/* Fetch data from API */}
      <div>
        <button className="fetch-button" onClick={fetchData}>
          download users
        </button>
        <br />
      </div>

      {/* Display data from API */}
      {}
      <div className="users">
       {groupedUsers && groupedUsers.map(n => (
  <div id="months" key={n.month}  className={n.users > 0 ? classes.month.grey  : n.users > 2 ? 
        classes.blue : n.users > 6 ? classes.green : classes.red} 
onMouseLeave={() => setVisibility(false)}
onMouseOver={() => setVisibility(true)}>
    <h2>{n.month}</h2>
    {n.users.map(user => (
      usersVisible ? 

      <div key={user.id} >

        <div>
         <h4 className={classes.userId}>user #{user.id}</h4>
        данные пользователя...</div>
      </div> : null
    ))}
  </div>
))}
      </div>
    </div>
  );
}

Finally, I've noticed that you are fetching data for your component, so consider using useEffect hook , as it's the recommented approach for data fetching in a function component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM