在React Native中将新对象添加到数组

时间:2020-10-01 08:59:45

标签: javascript reactjs react-native expo react-native-flatlist

我已经创建了一个表格,用于在主屏幕上上传图像和文本字段,但是我面临一个问题,即它不更新数组,因此验证失败。我认为我的实现存在问题

AddPost.js

const validationSchema = Yup.object({
  title: Yup.string().required().min(5).max(15).label("Title"),
  des: Yup.string().required().min(15).max(200).label("Description"),
  image: Yup.array().required().label("Image"),
});

class AddPost extends Component {
  render() {
    return (
      <Formik
        initialValues={{ title: "", des: "", image: [] }}
        onSubmit={(values, actions) => {
          actions.resetForm();
          this.props.addPost(values);
        }}
        validationSchema={validationSchema}
      >
        {(value) => (
          <View>
            <FormImage />
            <Text style={styles.error}>
              {value.touched.image && value.errors.image}
            </Text>
            <TextInput
              placeholder="Title"
              onChangeText={value.handleChange("title")}
              style={styles.input}
              value={value.values.title}
              onBlur={value.handleBlur("title")}
            />
            <Text style={styles.error}>
              {value.touched.title && value.errors.title}
            </Text>

这是我的表单字段,我想一切都在这里

home.js

class Home extends Component {
  state = {
    modal: false,
    post: [
      {
        key: "1",
        title: "A Good Boi",
        des: "He's a good boi and every one know it.",
        image: require("../assets/dog.jpg"),
      },
      {
        key: "2",
        title: "John Cena",
        des: "As you can see, You can't see me!",
        image: require("../assets/cena.jpg"),
      },
    ],
    image: null,
  };


  addPost = (posts) => {
    posts.key = Math.random().toString();
    this.setState.post((currentPost) => {
      return [posts, ...currentPost];
    });
    this.state.modal();
  };

  render() {
    return (
      <Screen style={styles.screen}>
        <Modal visible={this.state.modal} animationType="slide">
          <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
            <View style={styles.modalContainer}>
              <AddPost addPost={() => this.addPost} />
            </View>
          </TouchableWithoutFeedback>
        </Modal>
        <FlatList
          data={this.state.post}
          renderItem={({ item }) => (
            <>
              <Card
                title={item.title}
                subTitle={item.des}
                image={item.image}
                onPress={() => this.props.navigation.navigate("Edit", item)}
              />
            </>

我认为addPost方法出了点问题,因为我之前是用函数库做过的,那时候我只是将文本添加到列表中并且它起作用了,但是在类库中我不知道这样做,我只是尝试用相同的方式在功能库中完成

FormImage.js

class FormImage extends Component {
  state = {
    image: null,
    hasCameraPermission: null,
  };

  async componentDidMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    this.setState({ hasCameraPermission: status === "granted" });
  }

  _pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
    });

    if (!result.cancelled) {
      this.setState({ image: result.uri });
    }
  };

  render() {
    const { image } = this.state;
    return (
      <TouchableWithoutFeedback onPress={this._pickImage}>
        <View style={styles.container}>
          {!image && (
            <MaterialCommunityIcons
              color={colors.medium}
              name="camera"
              size={40}
            />
          )}
          {image && <Image style={styles.image} source={{ uri: image }} />}
        </View>
      </TouchableWithoutFeedback>
    );
  }
}


提交后 enter image description here

2 个答案:

答案 0 :(得分:1)

我假设您的addPost函数逻辑错误,

尝试以下代码

 addPost = (posts) => {
    posts.key = Math.random().toString();
    this.setState((prevState) => {
      return {...prevState, post: [...prevState.post, ...posts] };
    });
    this.state.modal();
  };

如果您遇到相同的错误,请告诉我。

答案 1 :(得分:0)

您没有将图像更新为formik,因此正常情况下会出现所需的错误。 首先,在AddPost组件中,将formikProps传递到FormImage组件。

while(ptr->pointer != NULL) {
    ptr = ptr->pointer;
}

在FormImage中,使用该formikProps并调用setFieldValue(“ image”,result.uri)来更新图像的formik值。

return (
      <Formik
        initialValues={{ title: "", des: "", image: [] }}
        onSubmit={(values, actions) => {
          // actions.resetForm(); --> comment this
          this.props.addPost(values);
        }}
        validationSchema={validationSchema}
      >
        {(value) => (
          <View>
            <FormImage formikProps={value}/>
            <Text style={styles.error}>
              {value.touched.image && value.errors.image}
            </Text>
            <TextInput
              placeholder="Title"
              onChangeText={value.handleChange("title")}
              style={styles.input}
              value={value.values.title}
              onBlur={value.handleBlur("title")}
            />
            <Text style={styles.error}>
              {value.touched.title && value.errors.title}
            </Text>

在家

class FormImage extends Component {
  state = {
    image: null,
    hasCameraPermission: null,
  };

  async componentDidMount() {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    this.setState({ hasCameraPermission: status === "granted" });
  }

  _pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
    });

    if (!result.cancelled) {
      this.setState({ image: result.uri });
      this.props.formikProps.setFieldValue("image", result.uri);
    }
  };

  render() {
    const { image } = this.state;
    return (
      <TouchableWithoutFeedback onPress={this._pickImage}>
        <View style={styles.container}>
          {!image && (
            <MaterialCommunityIcons
              color={colors.medium}
              name="camera"
              size={40}
            />
          )}
          {image && <Image style={styles.image} source={{ uri: image }} />}
        </View>
      </TouchableWithoutFeedback>
    );
  }
}