3

我有一个产品列表,我希望用户能够从列表中选择一个或多个。

如果我第一次单击/选择产品,console.log则会显示正确的结果。但是,如果我单击两次或更多次,则会收到错误消息:

TypeError:无法读取 null 的属性“值”

我尝试了两种不同的策略,但都失败了(检查功能addSelectedProducts):

第一个解决方案

function SearchProductForm() {
    const [selectedProducts, setSelectedProducts] = React.useState([]);

    function handleSubmit(event){
        event.preventDefault();
        }

    function addSelectedProducts(event) {
        console.log(event.target.value)
        setSelectedProducts(oldArray => [...oldArray, event.target.value]);
        console.log(selectedProducts)
    }

        return (
            <div>
                <Form>
                    <Form.Group controlId="exampleForm.ControlSelect2">
                        <Form.Label>Select the product(s) you are interested about:</Form.Label>
                        <Form.Control as="select" multiple onChange={(event) => addSelectedProducts(event)}>
                            <option value="product1">product1</option>
                            <option value="product2">product2</option>
                            <option value="product3">product3</option>
                            <option value="product4">product4</option>
                            <option value="product5">product5</option>
                        </Form.Control>
                    </Form.Group>
                    <Button variant="primary" type="submit" onClick={()=>handleSubmit()}>
                        Submit
                    </Button>
                </Form>
            </div>
        );
    }

export default SearchProductForm;

第二种解决方案

function SearchProductForm() {
    const [selectedProducts, setSelectedProducts] = React.useState([]);

function handleSubmit(event){
    event.preventDefault();
    }

function addSelectedProducts(event) {
    let options = event.target.options
    for (var i = 0, l = options.length; i < l; i++) {
        if (options[i].selected) {
            setSelectedProducts(oldArray => [...oldArray, event.target.value]);
            console.log(selectedProducts)

        }
    }
}

    return (
        <div>
            <Form>
                <Form.Group controlId="exampleForm.ControlSelect2">
                    <Form.Label>Select the product(s) you are interested about:</Form.Label>
                    <Form.Control as="select" onChange={(event) => addSelectedProducts(event)} multiple>
                        <option value="product1">product1</option>
                        <option value="product2">product2</option>
                        <option value="product3">product3</option>
                        <option value="product4">product4</option>
                        <option value="product5">product5</option>
                    </Form.Control>
                </Form.Group>
                <Button variant="primary" type="submit" onClick={()=>handleSubmit()}>
                    Search
                </Button>
            </Form>
        </div>
    );
}
4

3 回答 3

3

Ricardo touched on event pooling in their answer but I want to propose a solution where you don't need to persist the event, that's a bit code-smelly for me.

You can grab all the selected options at once and then set them instead of trying to merge new state with old state.

function addSelectedProducts(event) {
  // Alternative if you need to target ie
  // const selectedOptions = [...event.target.options].filter(o => o.selected).map(o => o.value)

  const selectedOptions = [...event.target.selectedOptions].map(o => o.value)

  setSelectedProducts(selectedOptions)
}

The reason you're encountering the error above, is that

setSelectedProducts(oldArray => [...oldArray, event.target.value]);

is async and by the time the callback is invoked, your event is no longer around. See more here: https://reactjs.org/docs/events.html#event-pooling

https://codesandbox.io/s/zealous-haibt-hp6mp

于 2019-11-07T17:19:16.833 回答
1

嗨,您检查过文档吗?也许您必须添加event.persist()因为您正在处理event内部 a function

 function addSelectedProducts(event) {
        event.persist()
        console.log(event.target.value)
        setSelectedProducts(oldArray => [...oldArray, event.target.value]);
        console.log(selectedProducts)
    }

其他解决方案可能涉及将变量设置为event.target.value

 function addSelectedProducts(event) {
        let value = event.target.value;
        console.log(event.target.value)
        setSelectedProducts(oldArray => [...oldArray, event.target.value]);
        console.log(selectedProducts)
    }

于 2019-11-07T15:24:05.507 回答
0

我认为你可以尝试onChange={addSelectedProducts}而不是onChange={(event) => addSelectedProducts(event)}

于 2019-11-07T15:12:36.370 回答