简体   繁体   中英

REACT: How to update list after click button EDIT?

I have main component App which display category list. This list I get from server and dispay in view table in component Table.

Component App also have children component ChangeCategory . Using this component I can change title of some category.

Home.js:

const App = () => {

  const [value, setValue] = useState({
         list: [],
   });
useEffect(() => {
async function fetchData () => {
     const response =  await fetch(`путь`);
     const data = await response.json();
     setValue({
         list: data.data
    });
};
}, [])
 return (
    <div>
        <Table data = {value.list} />
        <ChangeCategory />
    </div>

After request in Home.js I get this response from server:

{"data": [ 
 {"title": "bmw", "description": "good"},
 {"title": "tesla", "description": "good"},
 {"title": "ford", "description": "good"} ]}

ChangeCategory.js (edit title using method PUT in form):

const  ChangeCategory = (props) => {
    const { /..... } = useFormik({  
      initialValues: {
          title: '',
      },
    onSubmit: async (formValues) => {
        const response = await fetch(`somepath`, {
           method: PUT,  
        } ) 
        const data = await response.json();  
       }});

   return (    
    <div>
      <form >   
       <input type="text"> </input>
          <button type="submit">Edit</button>
     </form>
   </div>);};

After request in Home.js I get this response from server:

{"model":  {"title": "mercedes","description": "good"} }

That is, in the response I get only what I edited and the new model title.

But I have problem:

After editing in the form my Title and clicking on the submit button, my list is not updated!

It only updates when I reload the page in the browser. And I need me to immediately see the title update in the list.

How to update list after click button EDIT?

React only re-renders components under certain conditions , such as if a prop of the component is updated. But you can always tell a component to update based on another condition.

Since you are already implementing the useEffect hook, you could set a rerender condition by adding a variable to the second argument of the hook (right now it's just an empty array which is also a valid argument) ~ any variable you put inside the array will trigger a re-render if its value changes.

Consider adding a boolean to the components state, shouldUpdate, and when the button is clicked set that to true. Then have it set back to false whenever the component renders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM