反应导航:如何将数组map()数据传递到新屏幕(例如,文章列表>单篇文章)

时间:2019-06-13 10:59:57

标签: reactjs react-native react-navigation

我正在从API中获取文章列表,并通过map()函数显示它们。我已经在ScrollView中成功地全部显示了它们。现在,我想显示我单击的一篇文章。

我已经在父块上声明了一个密钥。现在,我正在导航并将数据传递到另一个屏幕,但是无论如何,它都会传递“ undefined”。

Articles.js列表

    componentDidMount(){
      fetch(BASE_URL + PARAMS)
      .then(response => response.json())
      .then((responseJson) => {
        this.setState({
          loading:false,
          dataSource: responseJson.articles,
        }) 
      })
      .catch(error=>console.log(error))
    }


    renderArticles = () => {
      let articles = this.state.dataSource.map((article, key)=>{
        const { navigation, horizontal, style} = this.props;

        return (
          <Block key={key} row={horizontal} card flex style={[styles.product, styles.shadow, style]}>
            <TouchableWithoutFeedback onPress={() => navigation.navigate('Article', {article})}>
              <Block flex style={[styles.imageContainer, styles.shadow]}>
                <Image source={{ uri: article.image }} style={styles.fullImage} />
              </Block>
            </TouchableWithoutFeedback>
            <TouchableWithoutFeedback>
              <Block flex space="between" style={styles.productDescription}>
                <Text size={16} style={styles.productTitle}>{article.title}</Text>
                <Text size={14} style={styles.productDescription}>{article.short_description}</Text>
                <Text size={12} >Posted on: {article.created_at}</Text>
                <Text size={12} >Key: {key}</Text>

              </Block>
            </TouchableWithoutFeedback>
          </Block>
        );
      });

      return (

          <ScrollView
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.articles}>
            <Block flex>
              {articles}
            </Block>
          </ScrollView>

      )
    }

    render() {
      return (
        <Block flex center style={styles.home}>
          {this.renderArticles()}
        </Block>
      );
    }

Article.js

    render() {
        const { navigation, article} = this.props;
            return (
                 <Text >{article.title}</Text>
            )

    }

1 个答案:

答案 0 :(得分:1)

我认为您需要使用getParam()再次检索参数。请参阅文档here

在Article.js中执行以下操作:

render() {
    const { navigation} = this.props;
    const article = navigation.getParam("article"); 
    return (
       <Text >{article.title}</Text>
    );

}