如果我的 list.lenght> 10,我的任务是导航到另一个屏幕。
我的列表已使用hooks redux正确更新。
我有ActionSheetIOS.showActionSheetWithOptions,当我按“ go”时,我想检查一个list.lenght并检查它是否大于10。
状态(list.lenght)正确更新,但在我的函数中未更新。在我的职能中,状态是第一个状态。
我试图将函数放入useEffect中,我认为在更新列表时该值会更新,但是不会。
这是我的代码
export default function CustomersList(props) {
const userId = useSelector(state => state.loggedReducer.userId);
const customers = useSelector(state => state.customers.customers);
const dispatch = useDispatch();
const [refreshing, setRefreshing] = React.useState(false);
const onRefresh = React.useCallback(() => {
dispatch(fetchCustomers(userId));
}, []);
/**
* Add Right icon on header
* */
React.useLayoutEffect(() => {
props.navigation.setOptions({
headerRight: () => (<Ionicons name="ios-more" size={24} color="white" onPress={() => {onPress()}} style={{marginRight: 20}}/>),
});
}, [props.navigation]);
let clickGo;
const onPress = () => {
console.log("rendered");
ActionSheetIOS.showActionSheetWithOptions(
{
options: ["Cancel", "go"],
cancelButtonIndex: 0,
},
buttonIndex => {
switch (buttonIndex) {
case 0: // cancel Action
break;
case 1: // Go
clickGo();
break;
}
}
);
}
useLayoutEffect(() => {
console.log(customers.length); // updated state
clickGo = () => {
console.log("state", customers.length); // old state :(
if(customers.length < 10){
props.navigation.navigate("NewCustomer");
}else{
alert("upgrade to premium")
}
}
}, [customers])
}
答案 0 :(得分:0)
设置clickGo
的逻辑有些偏离-最简单的解决方法是删除此逻辑并将其全部放入onPress
const onPress = () => {
console.log("rendered");
ActionSheetIOS.showActionSheetWithOptions(
{
options: ["Cancel", "go"],
cancelButtonIndex: 0,
},
buttonIndex => {
switch (buttonIndex) {
case 0: // cancel Action
break;
case 1: // Go
if (customers.length < 10) {
props.navigation.navigate("NewCustomer");
} else {
alert("upgrade to premium")
}
break;
}
}
);
}
还要-确保将依赖项添加到onRefresh
中的数组中!
答案 1 :(得分:0)
我找到了解决方案,已将所有脚本放入这样的useEffect中。
useEffect(() => {
console.log(customers.length);
props.navigation.setOptions({
headerRight: () => (<Ionicons name="ios-more" size={24} color="white" onPress={() => {onPress()}} style={{marginRight: 20}}/>),
});
const onPress = () => {
ActionSheetIOS.showActionSheetWithOptions(
{
options: ["Cancel", strings.createNewCustomer, strings.connectWithCustomer],
cancelButtonIndex: 0,
},
buttonIndex => {
switch (buttonIndex) {
case 0: // cancel Action
break;
case 1: // Create new Client Action
if(!premium){
if(customers.length < 10){
props.navigation.navigate("NewCustomer");
}else {
Alert.alert(strings.upgradeToPremium)
}
}else {
props.navigation.navigate("NewCustomer");
}
break;
case 2: // Connect
if(!premium){
if(customers.length < 10){
openConnectModal();
}else {
Alert.alert(strings.upgradeToPremium)
}
}else {
openConnectModal();
}
break;
}
}
);
}
}, [customers])