【问题标题】:How can I create a React Native Button that saves an array value and the Button state to the device using AsyncStorage?如何使用 AsyncStorage 创建一个将数组值和 Button 状态保存到设备的 React Native Button?
【发布时间】:2021-06-20 21:48:36
【问题描述】:

我正在尝试创建一个在单击时更改文本并将值保存到数组的按钮。然后我需要使用 AsyncStorage 将按钮和数组的状态保存到设备中。

我已经完成了第一部分(请参阅 Snack 链接 here),但我正在努力让 AsyncStorage 正常工作。如果该按钮已被单击一次,我希望该数组中包含“item 1”值,并且该按钮会显示已单击。即使应用程序已关闭并重新打开,这些值仍应保留,直到再次单击该按钮。

到目前为止,我还没有找到任何解决方案。有没有人有一些想法?

【问题讨论】:

    标签: react-native react-redux asyncstorage


    【解决方案1】:

    这是您应该遵循的工作流程:

    • 为按钮的文本值创建一个状态对象(在 this.state = {} 中用于类,或 setState() 与钩子)
    • 使用 AsyncStorage 中的值初始化上述值(确保添加一些条件,如果它为空则返回 [])
    • 还要注意 Asyncstorage 是如何异步的,这意味着您在分配值时必须添加“等待”
    • 为按钮的文本值添加一些条件,而它会在 AsyncStorage 检索初始数据时显示加载图标(或什么都没有,没关系)
    • onPress 按钮将更改状态值和 AsyncStorage 值(或者您只能在使用 componentWillUnMount 关闭页面时更新 AsyncStorage 值,或者 useEffect(() => return(--do it here- -))

    如果您使用的是函数式组件,它看起来像这样:

    const [textValues, setTextValues] = useState([])
    
    const setInitialValues = async () => {
       const info = await AsyncStorage.getItem('myValues')
       setTextValues(info)
    }
    
    useEffect(() => {
       setInitialValues()
       return(
           AsyncStorage.setItem('myValues', textValues)
       )
    }, [])
    
    return(
        <View>
            <Button onPress={() => setTextValues(textValues + 1) title={textValues.length === 0 ? '' : textValues[textValues.length - 1]}}
        </View>
    
    )
    

    【讨论】:

    • 如果不使用功能组件,这将如何工作?
    • 你可以使用 state 的等价类来代替 useState。然后,您将其拆分为两个生命周期方法,而不是 useeffect:componentdidmount() 和 componentWillUnmount()。在前者中,您将从 asyncStorage 中获取项目,而在后者中,您将设置 asyncStorage 值。
    • 我仍然无法让它正常工作。我在原始帖子中包含了一个小吃链接。它偶尔会起作用,但并非始终如一。我无法弄清楚为什么我无法从 asynStorage 获得一致的结果。我尝试像您提到的那样包含 ComponentWillUnmount() ,但没有任何区别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多