简体   繁体   English

使用 onChange 更新组件。 反应钩子

[英]Update a component with onChange. React-Hooks

I'm building a dropdown with suggestions that fetch data from an API.我正在构建一个下拉列表,其中包含从 API 获取数据的建议。 The input from the search bar is being stored using setState and it is updated when i change the value in the text input.来自搜索栏的输入是使用 setState 存储的,当我更改文本输入中的值时,它会更新。

The thing is that I'm not managing to update the users lists from the dropdown each time I enter a new character in the text input.问题是每次我在文本输入中输入新字符时,我都无法从下拉列表中更新用户列表。 Can I somehow force the component to be rendered every time the props change?我可以以某种方式强制每次道具更改时渲染组件吗? Or is there a better approach?或者有更好的方法吗?

import React, {useState, useEffect} from 'react';
import Dropdown from '../Dropdown/Dropdown';
import './SearchBar.css';


// Component created with arrow function making use of hooks
const SearchBar = (props) => {

    const [input, setInput] = useState('');
    const [dropdownComponent, updateDropdown] = useState(<Dropdown input={input}/>)

    useEffect(() => {updateDropdown(<Dropdown input={input}/>)}, [input])

    const onChange = (e) => {
        setInput(e.currentTarget.value)
        updateDropdown(<Dropdown input={input}/>)
        console.log("=(")
    }



    return(
        <div className="search-bar">
            <input type="text" placeholder={props.placeholder} onChange={onChange}/>
            {dropdownComponent}
        </div>

    )
}

export default SearchBar;

I can't make the problem happen using your code in a simple test, but your onChange does has a problem: It's using input to update the dropdown, but it's not using useCallback to ensure that input isn't stale when it does.我无法在简单的测试中使用您的代码来解决问题,但是您的onChange确实存在问题:它使用input来更新下拉列表,但它没有使用useCallback来确保input在它发生时不会过时。 Either:任何一个:

  1. Don't update the dropdown in your onChange , allowing your useEffect callback to do it;不要更新onChange的下拉菜单,让useEffect回调来做; or或者

  2. Use e.target.value instead of input and get rid of the useEffect updating the dropdown;使用e.target.value代替input并去掉useEffect更新下拉菜单; or或者

  3. Don't memoize the dropdown (eg, don't put it in state) since you want to update it when the input changes anyway, just render it directly in the JSX不要记住下拉列表(例如,不要将其置于状态),因为无论如何您都想在输入更改时更新它,只需直接在 JSX 中呈现它

Of those, with what you've shown, #3 is probably the simplest:其中,根据您所展示的内容,#3 可能是最简单的:

const SearchBar = (props) => {

    const [input, setInput] = useState('');

    const onChange = (e) => {
        setInput(e.currentTarget.value);
    };

    return(
        <div className="search-bar">
            <input type="text" placeholder={props.placeholder} onChange={onChange}/>
            <Dropdown input={input}/>
        </div>
    );
}

Live Example:现场示例:

 const {useState, useEffect} = React; function Dropdown({input}) { return <div>Dropdown for "{input}"</div>; } const SearchBar = (props) => { const [input, setInput] = useState(''); const onChange = (e) => { setInput(e.currentTarget.value); }; return( <div className="search-bar"> <input type="text" placeholder={props.placeholder} onChange={onChange}/> <Dropdown input={input}/> </div> ); } ReactDOM.render(<SearchBar />, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在更新 state 和 react-hooks 时执行异步代码 - Executing async code on update of state with react-hooks React / React-Hooks:需要在React Hooks组件中运行onLoad函数 - React/React-Hooks: Need to run a function onLoad within React Hooks component 在2个下拉菜单之间传递值。 更新无需点击 - Passing value between 2 dropdowns onchange. Update without click React挂钩:如何使用react-hooks / exhaustive-deps规则在没有无限循环的情况下读取和更新挂钩中的状态 - React hooks: How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule 根据 react-hooks 功能组件中的搜索结果更新子组件 - updating the Child Component based on search results in react-hooks functional components 计数增量器未在反应挂钩中设置状态 - Count Incrementer not setting state in react-hooks 仅更新我更改其他人的日期 state 不应更新或更改 ReactJS/React-Hooks - Only update the date I change others state should not update or change ReactJS/React-Hooks React-Hooks:在 ContextAPI 中未定义“警报” - React-Hooks: 'Alert' is undefined in ContextAPI 将样式更改为单个项目 React-Hooks - Change style to individual item React-Hooks 使用 React-Hooks 单击按钮后如何显示不同的组件? - How to display different component after button click using React-Hooks?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM