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

时间:2021-06-16 06:42:45

标签: reactjs react-hooks

我正在尝试使用引导程序创建动态下拉列表。此下拉列表中的项目将根据上一个下拉列表中选择的值而变化。上一个下拉列表中的值更改成功,状态也会更改,但每次选择后 {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>
   ...
 )

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

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

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

add_action('add_meta_boxes', 'book_isbn_meta_box');
function book_isbn_meta_box()
 {
   add_meta_box(
     'book_isbn_meta_box',
     'Book ISBN',
     'book_isbn_meta_box_content',
     'books',
   );
  }

function book_isbn_meta_box_content($post)
 {
   wp_nonce_field(plugin_basename(__FILE__), 'book_isbn_meta_box_content_nonce');
   ?>
    <label for="isbn"></label>
    <input type="text" id="isbn" name="isbn" placeholder="Enter ISBN" />
   <?php
 }
add_action('save_post', 'book_isbn_meta_box_save');
function book_isbn_meta_box_save($post_id)
 {
   $isbn = $_POST['isbn'];
   global $wpdb;
   $table_name = $wpdb->prefix . "books_info";
   $wpdb->insert($table_name, array('post_id' => $post_id, 'isbn' 
    => $isbn) );
 }
// 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"));

相关问题