即使 useState 值已更改,组件也不会更新

问题描述 投票:0回答:3

我正在尝试使用引导程序创建动态下拉菜单。此下拉列表中的项目将根据上一个下拉列表中选择的值而变化。上一个下拉列表中的值成功更改,状态也更改,但 {userName} 在每次选择后不会重新渲染。

const users = ... // API call from server 

const [userName, setUserName] = useState([]);

useEffect(() => {
   console.log(userName) // userName successfully changes at each select
}, [userName]);

function handleSelect(event) {
   setUserName(event.target.value)
}

return (
   ...
   <Form.Group> 
      <Form.Label>
         Select User
      </Form.Label>

      // This part works fine 
      <Form.Control 
          as="select" 
          onChange={handleSelect} 
          className="form-select"
      > 
           {users.map(names => {
               <option key={names.value} > {names.name} </option>
           }
     </Form.Control> 

    <Dropdown> 
       // userName doesnt change 
       <Dropdown.Item> {userName} </Dropdown.Item> 
    <Dropdown>
   ...
 )
reactjs react-hooks
3个回答
1
投票

我使用了您提供的相同代码,它对我有用。

也许这个片段对你有帮助。

// Get a hook function

const { useState, useEffect, Fragment } = React;
const { Form, Dropdown, Row, Col, Container } = ReactBootstrap;

const Example = ({}) => {
    const [userName, setUserName] = useState([]);
    const users = [
        { name: "abc", value: "abc" },
        { name: "xyz", value: "xyz" }
    ];

    function handleSelect(event) {
        setUserName(event.target.value);
    }

    return (
        <Container>
            <Row>
                <Col sm={6}>
                    <Form.Label>Select User</Form.Label>
                    <Form.Control as="select" onChange={handleSelect} className="form-select">
                        {users.map((val) => {
                            return <option key={val.value}> {val.name} </option>;
                        })}
                    </Form.Control>
                </Col>
            </Row>
            <Row>
             <Form.Label>Selected Value:</Form.Label>
                <Dropdown>
                    <Dropdown.Item>{userName}</Dropdown.Item>
                </Dropdown>
            </Row>
        </Container>
    );
};

// Render it
ReactDOM.render(<Example title="Example using Hooks:" />, document.getElementById("react"));
<link
  rel="stylesheet"  href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
  integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
  crossorigin="anonymous"
/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

<script
  src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"
  crossorigin></script>
<div id="react"></div>


0
投票

注意https://reactjs.org/docs/hooks-reference.html#usestate

与类组件中的 setState 方法不同,useState 不会自动合并更新对象。您可以通过将函数更新器形式与对象扩展语法相结合来复制此行为:

        function handleSelect(event) {
           setUserName((prevValues) => return [...prevValues, event.target.value])
        }

0
投票

您未能将事件对象传递给您的handleSelect 函数。示例: onChange={(event)=>{handleSelect(event)} 然后在您的函数中:handleSelect (event){ setUserName(event.target.value) }

© www.soinside.com 2019 - 2024. All rights reserved.