【发布时间】:2020-08-19 13:59:15
【问题描述】:
如果我的 list.lenght 大于 10,我的任务是导航到另一个屏幕。
我的 list 已使用 hooks e 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])
}
【问题讨论】:
-
你为什么使用
useLayoutEffect? -
这是我最后一次尝试,在我使用 useEffect 之前。但结果是一样的。我的状态没有更新
标签: reactjs react-native react-hooks react-native-ios use-effect