Typescript React Native 图像选择器双击问题(非博览会)

问题描述 投票:0回答:1

所以,有一些好消息和一些坏消息。

好消息是下面的代码可以工作。

坏消息是我必须选择图像两次才能显示客户端。

导入代码:

import {launchImageLibrary} from 'react-native-image-picker'

设置状态:

const [loading1, setLoading1] = useState(false)
const [ image, setImage ] = useState('')

      const [post, setPost] = useState([
        {
          title: '',
          image: '',
          user
        }
      ])

图像选择器代码:

      const uploadImage = async ( index: number )=>{ 
      setLoading1(true)
      const result = await launchImageLibrary({
        mediaType: 'mixed',
        quality: 1
      }).then(res =>{
        if(!res.didCancel){
          let data = res.uri || res.assets?.[0]?.uri
          setImage(data)
        }
        
      })
        if(image){
          setPost(prevPost =>{
            const updatedPost = [...prevPost]
            updatedPost[index] = {
              ...updatedPost[index],
              image: image 
            }
            return updatedPost 
          })   
        }
       console.log('RESULT=====> ', image)   
      setLoading1(false)
    }

prevPost
代码仅用于将图像添加到表单帖子中的其他元素。我怀疑上面的代码中缺少一些东西,导致我必须触摸下面的可触摸不透明度,从手机中选取图像,然后发布......两次。

我第二次这样做可以,但第一次不行。显然,我想要的是只需触摸可触摸不透明度,选择图像,然后在我第一次运行该过程时显示它。我不知道我在这里缺少什么。欢迎任何建议。

无论如何,这是返回代码:

            {
              post.map(( item, index )=>(
                <View key={index}>
                  <TouchableOpacity onPress={()=>uploadImage(index)}>
                    <AntDesign name="link" size={20} color="black" />
                  </TouchableOpacity>     
                 
                  {
                    item.image && (
                        <Image style={styles.nft_image} resizeMode='contain' source={{ uri: item.image }} />
                    ) 
                   } 
                 
                </View>
                
              ))
            }

javascript typescript react-native command-line-interface react-native-image-picker
1个回答
0
投票

useState
是一个异步函数,这就是您可能会看到这个的原因。具体来说,
setImage
不会立即更改图像的状态,因此在设置后立即检查
if(image)
可能仍会给出空图像状态。

可以通过将 post 状态的更新逻辑移至

launchImageLibrary
调用的 then 块来解决此问题,以确保它仅在图像状态发生更改后执行。

试试这个

const uploadImage = async (index: number) => {
  setLoading1(true);
  const result = await launchImageLibrary({
    mediaType: 'mixed',
    quality: 1,
  }).then((res) => {
    if (!res.didCancel) {
      let data = res.uri || res.assets?.[0]?.uri;
      setImage(data);

      // Update youre post state inside the then block
      setPost((prevPost) => {
        const updatedPost = [...prevPost];
        updatedPost[index] = {
          ...updatedPost[index],
          image: data,
        };
        return updatedPost;
      });
    }
  });
  
  setLoading1(false);
};

其他可能有帮助的答案:React Native | useState 异步等待

© www.soinside.com 2019 - 2024. All rights reserved.