React Native TypeError:使用Formik传播不可迭代实例的无效尝试

时间:2020-07-22 01:52:17

标签: javascript reactjs react-native

我正在从Mosh编码教程中学习React Native。尝试在产品列表页面顶部显示图像列表时遇到问题。在示例中,他逐步创建了组件,并最终将其实现到屏幕中。在他要求我将其实现为表单之前,我先完成了ImageInputList的工作。这是问题开始的时间。我基本上已经复制了他的源代码,但仍然收到错误。我只是想了解为什么会发生这种情况,因此我可以更改其实现方式。

处理轻击的组件,如果选中该组件,则呈现图像(ImageInput.js):

function ImageInput({ imageUri, onChangeImage }) {
  useEffect(() => {
    requestPermission();
  }, []);

  const requestPermission = async () => {
    const { granted } = await ImagePicker.requestCameraRollPermissionsAsync();
    if (!granted) alert("You need to enable permission to access the library.");
  };

  const handlePress = () => {
    if (!imageUri) selectImage();
    else
      Alert.alert("Delete", "Are you sure you want to delete this image?", [
        { text: "Yes", onPress: () => onChangeImage(null) },
        { text: "No" },
      ]);
  };

  const selectImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        quality: 0.5,
      });

      if (!result.cancelled) onChangeImage(result.uri);
    } catch (error) {
      console.log("Error reading an image", error);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={handlePress}>
      <View style={styles.container}>
        {!imageUri && <Icon color="gray" name="camera" size={40} />}
        {imageUri && <Image source={{ uri: imageUri }} style={styles.image} />}
      </View>
    </TouchableWithoutFeedback>
  );
}
export default ImageInput;

由以下ImageInputs(ImageInputList.js)组成的列表:

function ImageInputList({ imageUris = [], onRemoveImage, onAddImage }) {
  const scrollView = useRef();

  return (
    <View>
      <ScrollView
        ref={scrollView}
        horizontal
        onContentSizeChange={() => scrollView.current.scrollToEnd()}
      >
        <View style={styles.container}>
          {imageUris.map((uri) => (
            <View key={uri} style={styles.image}>
              <ImageInput
                imageUri={uri}
                onChangeImage={() => onRemoveImage(uri)}
              />
            </View>
          ))}
          <ImageInput onChangeImage={(uri) => onAddImage(uri)} />
        </View>
      </ScrollView>
    </View>
  );
}

以前的组件和错误消息的组合,以便我可以更轻松地使用该组件(FormImagePicker.js):

export default function FormImagePicker({ name }) {
  const { errors, setFieldValue, touched, values } = useFormikContext();
  const imageUris = values[name];

  const handleAdd = (uri) => {
    setFieldValue(name, [...imageUris, uri]);
  };

  const handleRemove = (uri) => {
    setFieldValue(
      name,
      imageUris.filter((imageUri) => imageUri !== uri)
    );
  };

  return (
    <>
      <ImageInputList
        imageUris={imageUris}
        onAddImage={handleAdd}
        onRemoveImage={handleRemove}
      />
      <ErrorMessage error={errors[name]} visible={touched[name]} />
    </>
  );
}

**正在(ListingEditScreen)**上实现的屏幕相关部分**

function ListingEditScreen(props) {
  return (
    <SafeScreen style={styles.container}>
      <AppForm
        initialValues={{
          title: "",
          price: "",
          description: "",
          category: null,
          images: [],
        }}
        onSubmit={(values) => console.log(values)}
        validationSchema={validationSchema}
      >
        <FormImagePicker name="images" />
        <AppFormField
          autoCapitalize="none"
          autoCorrect={false}
          keyboardType="default"
          maxLength={255}
          name="title"
          placeholder="Title"
        />

这是ImageInput组件中引发的错误: * 这是在selectImage函数中打印的,但是散布运算符位于组件FormImagePicker中。

Error reading an image [TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.]

0 个答案:

没有答案