简体   繁体   English

使用react钩子更新本地状态

[英]Updating local state with react hooks

I'm learning how to use hooks and have still a little trouble comprehending how to use local component state. 我正在学习如何使用挂钩,并且在理解如何使用本地组件状态方面仍然遇到一些麻烦。

In the following component I am fetching data to display as a list. 在以下组件中,我正在获取数据以显示为列表。 I store that in the local state and display the list. 我将其存储在本地状态并显示列表。

Now I want to delete an item from the list and update the current variable in the local state that displays the data and remove the one item i just deleted. 现在,我想从列表中删除一项,并在显示数据的本地状态下更新当前变量,并删除我刚刚删除的一项。

Question: How do I use the local state variable, in this case feeds in the deleteFeed method so I can update the list. 问:我使用本地状态变量,在这种情况下如何做feedsdeleteFeed方法,所以我可以更新列表。 In class based components I could have just used this.state.feeds to update but how is it done in function components? 在基于类的组件中,我本可以使用this.state.feeds进行更新,但是如何在功能组件中完成呢?

import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'

import * as FeedsAPI from '../../../lib/feeds/FeedsAPI'

import FeedsList from './components/FeedsList'
import AddNewFeed from './components/AddNewFeed'
import DSPageLoader from '../../../components/DSPageLoader/DSPageLoader'
import FeedCard from './components/FeedCard'

const AddNewFeedCard = FeedCard(AddNewFeed)

export default function Feeds (params) {
    const[feeds, setFeeds] = useState([])
    const[providers, setProviders] = useState([])
    const[loading, setLoading] = useState(true)
    const[error, setError] = useState(false)

    /**
     * Method used run after evey lifecycle event
     */
    useEffect( () => {      
        Promise.all(
            [
                FeedsAPI.getFeeds('id', 732),
                FeedsAPI.getFeedProviders()
            ]
        )
        .then( response => {
            setFeeds(response[0])
            setProviders(response[1])
            setLoading(false)
        })
        .catch( error => {setLoading(false); setError(error)})
    }, [])

    /** 
     * Update feeds in local state 
     * 
     * @param feed single feed object 
     */
    const updateFeed = (feed) => console.log(feed)

    /**
     * Delete feed
     * 
     * @param feedId 
     */
    const deleteFeed = (feedId) => {
        FeedsAPI.deleteFeed(feedId)
        .then( response => { 
            let updatedFeeds = feeds.filter( feed => feed.id != feedId )
            setFeeds(feeds)
        })
        .catch( error => console.log(error))
    }

    /* TODO: Refactor this to use with page loading HOC */
    if (loading) {
        return <DSPageLoader/>
    }

    return (
        <div className="container">
            <FeedsList 
                feeds={feeds} 
                providers={providers}
                updateFeed={updateFeed}
                deleteFeed={deleteFeed}
                />
            <AddNewFeedCard />
        </div>
    )
}

simple you just use the variable feeds, provided you have defined it BEFORE using it. 很简单,只要在使用变量提要之前就已对其进行定义,就可以使用它。 you have used it correctly with an error that updating you are not setting state to the updated feeds variable 您已正确使用它,但出现错误,即您没有将状态设置为已更新的提要变量

 let updatedFeeds = feeds.filter( feed => feed.id != feedId )
 setFeeds(updatedFeeds) // you were setting it to the old unchanged feeds variable

remember filter function never modifies the original variable it always creates a new object which is modified 请记住,过滤器函数从不修改原始变量,它总是创建一个新对象,该对象被修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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