反应显示最后一个状态

时间:2020-05-16 14:43:35

标签: javascript reactjs

我的下面的代码需要一些帮助。

public function invoice($id)
    {
        $motorcycle_service = MotorcycleService::findOrFail($id);
        $invoice = \ConsoleTVs\Invoices\Classes\Invoice::make()
                ->number($motorcycle_service->id)
                ->with_pagination(true)
                ->duplicate_header(true)
                ->date(Carbon::parse($motorcycle_service->created_date))
                ->notes('Expected date and time to complete: ' . Carbon::createFromFormat('Y-m-d H:i:s', $motorcycle_service->expected_date)->format('d/m/Y h:i a'))
                ->customer([
                    'name'      => $motorcycle_service->motorcycle->customer->name,
                    'phone'     => $motorcycle_service->motorcycle->customer->phone_no,
                    'id'     => $motorcycle_service->motorcycle->customer->id,
                    'email' => $motorcycle_service->motorcycle->customer->email
                ]);

        foreach ($motorcycle_service->items as $item){
            $invoice->addItem($item->item->name, $item->item->price, $item->quantity, $item->id)            
        }

        return $invoice->show($motorcycle_service->id);
    }

当我单击“删除”按钮时,可以从import React, { useState, useEffect } from 'react'; import { Container, Row, Col, ListGroup, Button, InputGroup, FormControl } from 'react-bootstrap'; import FileUpload from './Components/FileUpload' const MyComponent = () => { //dump const importData = { myFields: ['field1', 'field2','field3','field4'], exampleData: { field1: "value1", field2: "value2", field3: "value3", field4: "value4" }, } const [currentSelectedField, setCurrentSelectedField] = useState(); const [currentSelectedValue, setCurrentSelectedValue] = useState(); const [selectedFields, setSelectedFields] = useState({}) const [currentItemToEdit, setCurrentItemToEdit] = useState() const [editValue, setEditValue] = useState(''); const [editKey, setEditKey] = useState(''); const alertDilog = (item) => { console.log(`You clicked the third ListGroupItem ${item}`); console.log(selectedFields[item]) let exampleData = importData.exampleData // console.log(exampleData) let exampleValue = exampleData[item]; setCurrentSelectedField(item); let selectedFieldsObject = selectedFields; console.log(selectedFieldsObject) selectedFields[item] = item console.log(selectedFieldsObject) setSelectedFields(selectedFieldsObject) // console.log(importProduct) //console.log(item) //console.log(exampleValue) setCurrentSelectedValue(exampleValue) } const showExample = (data) => { if (currentSelectedField) { if (data) { return ( <span>Example Data = {data} </span> ) } } else { return ( <span>You didnt select any field <br/> </span> ) } } const checkListData = (item) => { let flag = 0; Object.keys(selectedFields).map(function (keyName, keyIndex) { if (keyName === item) { flag = 1; } }) if (flag === 0) { return false } else { return true } } const selectForEditting = (keyName, value) => { console.log(keyName) setCurrentItemToEdit({ key: keyName, value: value }) setEditValue(value) setEditKey(keyName) } const selectToDelete = (keyName, value) => { let fields = selectedFields; delete fields[keyName]; console.log(fields) setSelectedFields(fields); } const showselectedItems = () => { // console.log('render') // console.log(item) console.log('existing!') if (selectedFields) { // console.log('here') // console.log(item) return ( <ListGroup defaultActiveKey="#link1"> {Object.keys(selectedFields).map((keyName, keyIndex)=> // use keyName to get current key's name // and a[keyName] to get its value <ListGroup.Item key={keyIndex} action> <Container fluid > <Row> <Col xs={8}>key : {keyName} <br /> value : {selectedFields[keyName]}</Col> <Col xs={2}> <Button size="sm" onClick={() => selectForEditting(keyName, selectedFields[keyName])} variant="outline-primary">Edit</Button></Col> <Col xs={2}> <Button size="sm" onClick={() => selectToDelete(keyName, selectedFields[keyName])} variant="outline-primary">x</Button></Col> </Row> </Container> </ListGroup.Item> )} </ListGroup> ) } else { return ( <span>No selected Fields</span> ) } } const handleProductEdit = (value) => { console.log(value) setEditValue(value) } const saveEditfield = (item) => { console.log('save fields') console.log(item) selectedFields[editKey] = editValue let selectedFieldsObject = item; Object.keys(selectedFieldsObject).map(function (keyName, keyIndex) { // use keyName to get current key's name // and a[keyName] to get its value if (keyName === editKey) { selectedFieldsObject[keyName] = editValue } }) console.log(selectedFieldsObject) setSelectedFields(selectedFieldsObject) } const showEditArea = () => { // console.log(currentItemToEdit) if (currentItemToEdit) { return ( <div> <InputGroup className="mb-3"> <InputGroup.Prepend> <InputGroup.Text id="basic-addon1">Value ({editKey}) </InputGroup.Text> </InputGroup.Prepend> <FormControl placeholder="New value" aria-label="New value" aria-describedby="basic-addon1" value={editValue} onChange={e => handleProductEdit(e.target.value)} /> </InputGroup> <Button onClick={() => saveEditfield(selectedFields)} variant="primary">Save</Button> </div> ) } } const showMainArea = () => { return (<div> <Row> <Col> {showExample(currentSelectedValue)} <ListGroup defaultActiveKey="#link1"> {importData.myFields.map(item => { return ( <ListGroup.Item className={'my-1'} key={item} active={checkListData(item)} onClick={() => alertDilog(item)}> {item} </ListGroup.Item> ) }) } </ListGroup> </Col> <Col>Custom Fields {showselectedItems()} </Col> <Col>Edit Area {showEditArea()} </Col> </Row> <Button variant="success" className={'my-2 mx-1 '}>Send</Button> </div>) } return ( <Container fluid> <Row> <Col> {JSON.stringify(selectedFields)} </Col> </Row> {showMainArea()} </Container>) } export default MyComponent; 中删除数据。但它不会显示在屏幕上。

例如:

  • 我点击了值1
  • 我删除了值1
  • 我在屏幕上看不到空的对象,但是当我单击值2时 我只能在屏幕上看到值2。

1 个答案:

答案 0 :(得分:2)

当您更改状态并将其设置为状态时,react不会重新渲染组件,因为它认为自引用以来,您的状态没有任何变化。

建议您在更新状态之前先克隆状态

const selectToDelete = (keyName, value) => {
    let fields = {...selectedFields}; // cloning it.
    delete fields[keyName]; // Not update the cloned data
    console.log(fields)
    setSelectedFields(fields); // Now this will trigger a re-render and reflect the change
}