首页 > 解决方案 > 组件获取道具未定义

问题描述

我正在尝试使用导航来导航并将道具传递给另一个组件,但由于某种原因,道具在目标屏幕中变得未定义。

我有一个带有平面列表的主屏幕,平面列表上的每个项目都会将用户移动到第二个屏幕,其中包含列表项中的相应数据。

这是主屏幕平面列表和导航功能:

async function showConversation(company: Company) { 
  const currentUser: User = await StorageHelper.retrieveEntity() as User;
  const from = currentUser.uid;
  const to = company.uid;
  
  console.log(from); <-- logs correctly
  console.log(to); <-- logs correctly
  
  navigation.navigate('Conversation', {to: to, from: from});
}

return ( 
  <FlatList<Company>
    data={companies}
    renderItem={({item}) => (
      <TouchableOpacity onPress={() => showConversation(item)}>
        <CompanyCard company={item} />
      </TouchableOpacity>
    )}
    keyExtractor={(item) => item.uid}
    showsVerticalScrollIndicator={false}
  />
)

这是我的对话屏幕:

interface conversationScreenProps {
  navigation: any;
  to: string
  from: string;
}

const ConversationScreen = ({
  navigation,
  to,
  from,
}: conversationScreenProps) => {
  const [messages, setMessages] = useState<Array<IMessage>>([]);
  const [chatMessage, setChatMessage] = useState<string>('');
  const socket = io('http://127.0.0.1:3000');
  
  console.log(to); <-- logs undefined
  console.log(from); <-- logs undefined
}

我看到了与这个类似的问题,但我仍然无法弄清楚为什么会这样。

标签: react-native

解决方案


参数在路由道具内部传递,它们不会作为单独的道具传递。您必须像下面这样访问它

const ConversationScreen = ({
  navigation,
  route
}: conversationScreenProps) => {
  const [messages, setMessages] = useState<Array<IMessage>>([]);
  const [chatMessage, setChatMessage] = useState<string>('');
  const socket = io('http://127.0.0.1:3000');
  
  console.log(route.params.to); <-- logs undefined
  console.log(route.params.from); <-- logs undefined
}

你可以在这里查看参考 https://reactnavigation.org/docs/params/


推荐阅读