onChange not updating React

谁说胖子不能爱 提交于 2021-01-28 14:00:00

问题


I've been working on this project for the last couple of hours and I was pretty sure that this final hour would be my last. No errors are appearing. My thinking is that when I pick a hero from the drop down, the page will update depending on my choice. I may have something that isn't firing that I'm not picking up on.

import React, {useEffect, useState} from 'react'
import axios from 'axios'
require("regenerator-runtime/runtime");

const App = () => {
    const [hero, selectedHero] = useState(
        'Select a Hero'
    );
    const handleChange = event => selectedHero(event.target.value);
    return(
        <HeroSelect heroSelect={hero} onChangeHeadline={handleChange} />
    );

};
const HeroSelect = ({heroSelect, onChangeHeadline}) => {
    const [data, setData] = useState({heroes: []});
    useEffect(() => {
        const fetchData = async () => {
            const result = await axios(
                'https://api.opendota.com/api/heroStats',
            );
            setData({...data, heroes: result.data});
        };
        fetchData();
    }, []);
    return (
        <div>
            <h1>{heroSelect}</h1>
            <select>
                {data.heroes.map(item => (
                    <option key={item.id} value={heroSelect} onChange={onChangeHeadline} >
                        {item.localized_name}
                    </option>
                ))}
            </select>
        </div>
    )
};
export default App

回答1:


Define your onChange={onChangeHeadline} on Select tag not on option tag

         <select onChange={onChangeHeadline}>
           {data.heroes.map(item => (
            <option key={item.id} value={item.localized_name}>
             {item.localized_name}
            </option>
            ))}
         </select>



回答2:


You should be firing your onChange event on the select tag itself.

<select onChange={onChangeHeadline} >
.....
.....
</select>



回答3:


I reckon you didn't declare an onChange on the select.




回答4:


Using This method:

<select id="lang" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>


来源:https://stackoverflow.com/questions/59727823/onchange-not-updating-react

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