【发布时间】: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