【问题标题】:React Native - Update Context in Consumer only works first timeReact Native - 在消费者中更新上下文仅在第一次工作
【发布时间】:2021-03-05 08:54:14
【问题描述】:

我正在尝试更新一个上下文,如消费者内部按钮点击中的计数器,它是第一次工作(增量 +1),但在第一次点击后,按钮似乎无法再次点击。

UserContext.js

import React from 'react'; import { createContext, useState } from "react";


export const UserContext = createContext();

const UserProvider = ({children}) => {
    
    const [context, setContext] = useState({count : 1,   update: () => {
        setContext((context) => ({
            count: context.count + 1
        }));
    }});


    return(
        <UserContext.Provider value={context}>
            {children}
        </UserContext.Provider>
    );


}

export default UserProvider;

index.js

import React, {useEffect, useState, useContext } from 'react';
import {ScrollView, Text, View , Button, StyleSheet, ActivityIndicator} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import { UserContext } from '../userContext.js';


export default Home = ({navigation}) => {

  return (
    <View style={styles.body}>

      <UserContext.Consumer>
      {({count, update}) => ( 
      <View>
        <Button
            onPress={update}
            title="Counter">
          </Button>
          
        <Text>{count}</Text>
      </View>
      )}
    </UserContext.Consumer>
    
    </View>

  );
};

【问题讨论】:

  • 您的代码是错误的,因为当您设置上下文时,您删除了更新功能。看我的回答

标签: reactjs react-native react-hooks jsx react-context


【解决方案1】:

如何定义和使用上下文

const UserProvider = ({children}) => {
    
    const [context, setContext] = useState(1)   

    //create a update function that setContext
    const update = () => {
       setContext(prev => prev+1);
    }


    return(
        <UserContext.Provider value={{ context, update }}>
            {children}
        </UserContext.Provider>
    );


}

在您的 index.js

export default Home = ({navigation}) => {

  return (
    { /* wrap your app in the provider */}
    <UserProvider>
         <App />
    </UserProvider>

  );
};


//App Component
const App = () => {

     const { context, update } = useContext(UserContext)
     return (<View>
              <Button onPress={update} title="Counter">Add Counter</Button>
             <Text>{context}</Text>
             </View>)
}

【讨论】:

  • 它的工作。我认为我应该使用消费者,为什么不使用它?
  • 你可以。您的代码不起作用的原因是因为当您更新时,您删除了更新功能。其次,由于你使用函数式组件,所以学习使用钩子是一个好习惯。它干净实用。
  • 你检查你的更新功能,它只设置计数。
猜你喜欢
  • 2022-08-08
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 2021-05-13
  • 2019-07-27
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多