为什么在Alert.alert()函数中表达数据时会发生错误?

时间:2019-01-22 02:01:01

标签: react-native

我想在Alert.alert()中放置一个标题,并在标题下显示数据。

  • 如果您能告诉我问题出在哪里以及如何解决,我将不胜感激。
import React, { Component } from "react";
import {
  TouchableOpacity,
  Text,
  View,
  ListView,
  TouchableHighlight,
  Dimensions,
  Image,
  Animated,
  StyleSheet,
  TextInput,
  ImageBackground,
  Alert,
  FlatList
} from "react-native";
import { SearchBar, ListItem, List } from "react-native-elements";
import Ionicons from "@expo/vector-icons/Ionicons";
import sitterdata from "../components/sitterdata";

const { width, height } = Dimensions.get("window");

/*
const datas = [
  {
    name: "Registers",
    route: "Registers",
    icon: "phone-portrait",
    bg: "#C5F442"
  },
  {
    name: "PetSitters",
    route: "PetSitters",
    icon: "easel",
    bg: "#C5F442"
  }
];
*/

export default class PetSitters extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: sitterdata,
      refreshing: false
    };
  }

  static navigationOptions = ({ navigation }) => {
    return {
      title: "Pet Sitters",
      headerLeft: (
        <TouchableOpacity
          style={{ padding: 5, paddingRight: 15 }}
          //dataArray={datas}
          onPress={() => navigation.openDrawer()}
        >
          <Ionicons name={"ios-menu"} size={35} color={"#fff"} />
        </TouchableOpacity>
      ),

      headerRight: (
        <TouchableOpacity
          style={{ padding: 5, paddingRight: 15 }}
          onPress={() => navigation.navigate("Add")}
        >
          <Ionicons name={"ios-add"} size={35} color={"#fff"} />
        </TouchableOpacity>
      )
    };
  };

  showAlert(navigation) {
    Alert.alert(
      "이 펫시터와 거래 하시겠습니까?",
      // this.item.bind(sitterdata.by),
      //"데이터 입력",
      this.state.data(sitterdata.by),
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },
        { text: "OK", onPress: () => navigation.navigate("Add") }
      ],
      { cancelable: false }
    );
  }

  async filterSearch(text) {
    const newData = sitterdata.filter(function(item) {
      const itemData = item.address.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    await this.setState({
      data: newData,
      text: text
    });
  }

  refreshData = () => {};

  renderItem = ({ item }) => {
    return (
      <TouchableHighlight style={styles.containerCell}>
        <View>
          <TouchableOpacity
            onPress={() => this.showAlert(this.props.navigation)}
          >
            <Image
              style={{
                width: width,
                height: 180,
                resizeMode: "stretch"
              }}
              source={{ uri: item.image }}
            />
          </TouchableOpacity>
          <View style={styles.footerContainer}>
            <View style={styles.imageUser}>
              <Image style={styles.imageAvatar} source={{ uri: item.user }} />
            </View>
            <View style={styles.footerTextContainer}>
              <Text style={styles.text}>{item.introduce}</Text>
              <Text style={[styles.text, styles.textTitle]}>
                {item.address}
              </Text>
              <Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <Animated.View
          style={[
            styles.content,
            {
              width: width,
              backgroundColor: "#dfe4ea",
              flex: 1,
              transform: [
                {
                  perspective: 450
                }
              ]
            }
          ]}
        >
          <SearchBar
            onChangeText={text => this.filterSearch(text)}
            placeholder={"여기에 입력하세요"}
            value={this.state.text}
            lightTheme
            containerStyle={{}}
          />
          <FlatList
            style={styles.listContainer}
            onRefresh={this.refreshData}
            renderItem={this.renderItem}
            refreshing={this.state.refreshing}
            data={this.state.data}
            keyExtractor={(item, index) => item.address}
          />
        </Animated.View>
      </View>
    );
  }
}
  • 上面的代码是完整的代码,并且该错误是由Alert.alert()标题下的数据表示形式生成的。

  • 我认为这与Alert.alert数据的表达方式有关,但是我找不到哪一部分是错误的。

showAlert(navigation) {
    Alert.alert(
      "이 펫시터와 거래 하시겠습니까?",
      // this.item.bind(sitterdata.by),
      //"데이터 입력",
      this.state.data(sitterdata.by),
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },
        { text: "OK", onPress: () => navigation.navigate("Add") }
      ],
      { cancelable: false }
    );
  }
export default (sitterdata = [
  {
    id: 1,
    image:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfMjk3/MDAxNTQ3NTEzMDI1MDEx.ODD9YUUNc5YSk4Zz1wTgxmpf_BRr154ekJ-vJQ1f3ocg.u1uIXInfJ3O2PTKFmKFaI46epH_e8IzD5TEB96K-eF4g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.43.png?type=w966",
    introduce: "강아지 전문 펫시터에요 잘부탁드립니다",
    address: "평택시 서정동",
    user:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfOTQg/MDAxNTQ3NTEyODU0NDk4.DcAvlx3CGY9pGFlgWZA7mIr6_SCt8h_gGaHYGAFlDIYg.bQ9kBiykOzlbxyIyQ3nTCO7lGw4NVmmIeDV7pz0OX94g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.28.54.png?type=w966",
    by: "수지"
  },
  {
    id: 2,
    image:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfMTMx/MDAxNTQ3NTEzMDMzMDgx.SbY_nsX7oK4UlZGzre6U5dLHinRfCoAYyvnSzXuZR7cg.5K3sX7E0bDpgyzDifD174hfQBOnJDtLVFqTe8BHH7Gcg.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.57.png?type=w966",
    introduce: "나의 반려견은 편안하고 주인님은 안심할 수 있게",
    address: "서울특별시 서초구",
    user:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfMjU2/MDAxNTQ3NTEyODY3MTE2.X4LDN12uIgRkOFrUChl0s9UnKiu9VOPEOkWbIRHPDpgg.DrmXUbVURwsTuGs5dlOL_wugRf1nnANxWSIN4jYkdX0g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.29.23.png?type=w966",
    by: "손예진"
  },
  {
    id: 3,
    image:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfOTIg/MDAxNTQ3NTEzMDM3MDAy.p_CNMU7vlCaELYpfuqf6H9GrCEPe9BzFdeNojFuKGc4g.65lwFvImqL2QgC01mNPzIUbY0tgBz4lukZplv9NZkJAg.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.43.14.png?type=w966",
    introduce: "밍밍이와 함꼐하는 좋은 친구들 :-)",
    address: "대전광역시 유성구",
    user:
      "https://postfiles.pstatic.net/MjAxOTAxMTVfMjY4/MDAxNTQ3NTEzMDE5MDI2.fmBkO0W8lFwWCzo3KrJ3EDkTTZ_NmAKH0wlF050XMcYg.GJ8JTbs5nQNosj1ZhkK-1lm-ah2LIAN7i_d3hjIQ4K8g.PNG.dea972/%EC%8A%A4%ED%81%AC%EB%A6%B0%EC%83%B7_2019-01-15_%EC%98%A4%EC%A0%84_9.42.09.png?type=w966",
    by: "문채원"
  }
]);

添加数据代码

showAlert(navigation) {
    Alert.alert(
      "이 펫시터와 거래 하시겠습니까?",
      // this.item.bind(sitterdata.by),
      //"데이터 입력",
      item.by,

      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },
        { text: "OK", onPress: () => navigation.navigate("Add") }
      ],
      { cancelable: false }
    );
  }

  async filterSearch(text) {
    const newData = sitterdata.filter(function(item) {
      const itemData = item.address.toUpperCase();
      const textData = text.toUpperCase();
      return itemData.indexOf(textData) > -1;
    });
    await this.setState({
      data: newData,
      text: text
    });
  }

  refreshData = () => {};

  renderItem = ({ item }) => {
    return (
      <TouchableHighlight style={styles.containerCell}>
        <View>
          <TouchableOpacity
            onPress={() => this.showAlert(this.props.navigation, item)}
          >
            <Image
              style={{
                width: width,
                height: 180,
                resizeMode: "stretch"
              }}
              source={{ uri: item.image }}
            />
          </TouchableOpacity>
          <View style={styles.footerContainer}>
            <View style={styles.imageUser}>
              <Image style={styles.imageAvatar} source={{ uri: item.user }} />
            </View>
            <View style={styles.footerTextContainer}>
              <Text style={styles.text}>{item.introduce}</Text>
              <Text style={[styles.text, styles.textTitle]}>
                {item.address}
              </Text>
              <Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );
  };

更正了答案,但未找到项目。

1 个答案:

答案 0 :(得分:0)

您不需要访问this.state.data函数内部的showAlert,实际上可以将该项传递给函数并使用它。我会将您的showAlert函数更新为以下内容

showAlert(navigation, item) {
  Alert.alert(
    "이 펫시터와 거래 하시겠습니까?",
    // this.item.bind(sitterdata.by),
    //"데이터 입력",
    item.by,
    [
      {
        text: "Cancel",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel"
      },
      { text: "OK", onPress: () => navigation.navigate("Add") }
    ],
    { cancelable: false }
  );
}

showAlert函数内部创建指向renderItem函数的链接时,我只是将您要使用的项目传递给该函数。

所以您的renderItem现在看起来像

renderItem = ({ item }) => {
  return (
    <TouchableHighlight style={styles.containerCell}>
      <View>
        <TouchableOpacity
          onPress={() => this.showAlert(this.props.navigation, item)} // here we now pass the item
        >
          <Image
            style={{
              width: width,
              height: 180,
              resizeMode: "stretch"
            }}
            source={{ uri: item.image }}
          />
        </TouchableOpacity>
        <View style={styles.footerContainer}>
          <View style={styles.imageUser}>
            <Image style={styles.imageAvatar} source={{ uri: item.user }} />
          </View>
          <View style={styles.footerTextContainer}>
            <Text style={styles.text}>{item.introduce}</Text>
            <Text style={[styles.text, styles.textTitle]}>
              {item.address}
            </Text>
            <Text style={[styles.text, styles.textBy]}>By {item.by}</Text>
          </View>
        </View>
      </View>
    </TouchableHighlight>
  );
};