axios 如何传递id参数以导航到详细信息组件?

4xy9mtcn  于 2023-10-18  发布在  iOS
关注(0)|答案(2)|浏览(136)

我试图导航到ProductDetailsScreen.js并查看一个独特产品的详细信息,目前我正在使用render方法中的参数id来转到独特产品,但不幸的是,我得到了错误:
TypeError:无法读取未定义的属性“params”
任何人都可以告诉我如何正确地做,或者如果有人有正确的方法来做,我会感激。下面是我正在努力做的事情:

AppNavigator.js:

import * as React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import HomeScreen from "../screens/HomeScreen";
import ProductsScreen from "../screens/ProductsScreen";
import ProductDetailsScreen from "../screens/ProductDetailsScreen";

const Stack = createStackNavigator();

function MainStackNavigator() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Products" component={ProductsScreen} />
        <Stack.Screen name="Details" component={ProductDetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default MainStackNavigator;

productDetailScreen.js:

function ProductDetailsScreen(props) {
  const [products, setProducts] = useState([]);
  const id = props.match.params.id;
  useEffect(() => {
    axios
      .get(`http://localhost:3000/api/products/id=${id}`)
      .then((res) => {
        setProducts(res.data.response);
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);

  const dispatch = useDispatch();
  const addItemToCart = (item) =>
    dispatch({ type: ADD_TO_CART, payload: item });
  return (
    <View style={styles.container}>
      <View style={styles.shoppingCartContainer}>
        <View style={styles.shoppingCart}>
          <ShoppingCartIcon />
        </View>
      </View>
      <View>
        <FlatList
          data={products}
          keyExtractor={(item) => item.id.toString()}
          ItemSeparatorComponent={() => Separator()}
          renderItem={({ item, index }) => (
            <View style={styles.productItemContainer}>
              <Image
                source={require(`../../assets/images/${index + 1}.jpg`)}
                style={styles.thumbnail}
              />

              <View style={styles.productItemMetaContainer}>
                <Text style={styles.row} numberOfLines={1}>
                  {item.id}
                </Text>
                <Text style={styles.row}>{item.name}</Text>

                <Text style={styles.row}> {item.categories}</Text>
                <Text style={styles.row}> {item.genders}</Text>
                <Text style={styles.row}> {item.brands}</Text>
                <Text style={styles.price}>$ {item.price}</Text>
                <View style={styles.buttonContainer}>
                  <TouchableOpacity
                    onPress={() => addItemToCart(item)}
                    style={styles.button}
                  >
                    <Text style={styles.buttonText}>Add to Cart +</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          )}
        />
      </View>
    </View>
  );
}

ProductsScreen.js:

function ProductsScreen() {
  const navigation = useNavigation();
  const [products, setProducts] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:3000/product/')
      .then((res) => {
        setProducts(res.data.response);
      })
      .catch((err) => {
        console.error(err);
      });
  }, []);

  const dispatch = useDispatch();
  const addItemToCart = (item) =>
    dispatch({ type: ADD_TO_CART, payload: item });
  return (
    <View style={styles.container}>
      <View style={styles.shoppingCartContainer}>
        <View style={styles.shoppingCart}>
          <ShoppingCartIcon />
        </View>
      </View>
      <View>
        <FlatList
          data={products}
          keyExtractor={(item) => item.id.toString()}
          ItemSeparatorComponent={() => Separator()}
          renderItem={({ item, index }) => (
            <View style={styles.productItemContainer}>
              <Image
                source={require(`../../assets/images/${index + 11}.jpg`)}
                style={styles.thumbnail}
              />

              <View style={styles.productItemMetaContainer}>
                <TouchableOpacity onPress={() => navigation.push("Details")}>
                  <Text style={styles.row} numberOfLines={1}>
                    {item.id}
                  </Text>
                </TouchableOpacity>
                <Text style={styles.row}>{item.name}</Text>

                <Text style={styles.row}> {item.categories}</Text>
                <Text style={styles.row}> {item.genders}</Text>
                <Text style={styles.row}> {item.brands}</Text>
                <Text style={styles.price}>$ {item.price}</Text>
                <View style={styles.buttonContainer}>
                  <TouchableOpacity
                    onPress={() => addItemToCart(item)}
                    style={styles.button}
                  >
                    <Text style={styles.buttonText}>Add to Cart +</Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          )}
        />
      </View>
    </View>
  );
}
t3irkdon

t3irkdon1#

你应该像下面这样使用导航功能

<TouchableOpacity onPress={() => navigation.navigate("Details",{id:1})}>

你也可以做

<TouchableOpacity onPress={() => navigation.push("Details",{id:1})}>

不同之处在于push会添加新的屏幕,而navigation会在屏幕已经在堆栈中时返回。

cdmah0mi

cdmah0mi2#

使用navigation.navigate("SCREEN_NAME", {YOUR_PARAM: "PARAM_VALUE"})传递参数
并在其他屏幕上使用this.props.route.params.YOUR_PARAM接收参数

相关问题