【问题标题】:Shoutem pass props to another screenShoutem 将道具传递到另一个屏幕
【发布时间】:2017-09-10 21:48:11
【问题描述】:

我已经成功将道具传递到另一个屏幕,但是如何在第二个屏幕上全局使用道具?

我需要能够在包括 render() 在内的所有函数中使用从屏幕 1 传递的道具,因为我正在使用道具中的数据进行 fetch 调用,并使用与 render() 调用相同的道具数据。

例如,我需要这样做:

constructor(props) {
    super(props);
    this.state = {
      data: [],
      rowData: this.props,
    }
  }

  getData() {
    this.setState({
      rowData: this.props
    });
    return fetch('https://mywebsite.com/'+this.state.rowData.something+'/myotherdata')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          data: responseJson.data
        });
      })
      .catch((error) => {
        console.error(error);
      });
  }

  componentDidMount() {
    this.getData();
  }

  render() {      

    return (
      <ScrollView>
        <Image styleName="large-banner" source={{ uri: rowData.image &&
        rowData.image ? rowData.image : undefined }}>
          <Tile>
            <Title>{rowData.name}</Title>
            <Subtitle>{rowData.createdAt.datetime}</Subtitle>
          </Tile>
        </Image>

        <Row>
          <Text>Company: {rowData.company}</Text>
        </Row>

        <Divider styleName="line" />

        <Row>
          <Icon name="laptop" />
          <View styleName="vertical">
            <Subtitle>Visit webpage</Subtitle>
            <Text>{rowData.url}</Text>
          </View>
          <Icon name="right-arrow" />
        </Row>

        <Divider styleName="line" />

        <View style={{paddingTop: 20}}>
          <Progress.Bar progress={this.state.data.progress * .1} width={200} />
        </View>

        <Divider styleName="line" />

      </ScrollView>
    );
  }

显然,我做的不对,但我想不通。我做错了什么?

这个question 详细解释了我的屏幕和fetch 电话。

编辑:我根据下面的答案进行了更改并更新了我的代码。屏幕加载,然后出现此错误:

undefined 不是一个对象(评估 'this.state.data.progress)

对于这一行:

<Progress.Bar progress={this.state.data.progress * .1} width={200} />

【问题讨论】:

    标签: ios react-native shoutem


    【解决方案1】:

    据我所知,您有两种选择:

    1) 当你第一次收到道具时,你可以将它们存储在你的组件状态中,然后你可以通过调用 this.state 在当前组件的任何地方引用它们

    2) 您可以使用 Redux 将所有数据存储在 Reducer 中,然后它们将在您在 mapStateToProps 中实例化并连接的每个组件中可用。

    选择哪一个,这取决于您需要遵循此架构的次数和组件数量。

    您可以在他们的官方文档中获得有关 Redux 的更多信息。这是他们提供的一个简单示例:http://redux.js.org/docs/basics/ExampleTodoList.html

    希望对你有帮助。

    【讨论】:

    • 我更新了我的问题,但不断收到错误消息。请参阅上面的更改。另外,如果您有一个非常有用的代码示例。
    • 您在 componentDidMount 上获取数据,因此您的渲染方法在您的 getData 之前运行。当您的组件尝试渲染它时,它期望 this.state.data 是一个包含“进度”键的对象,但是它在您的构造函数中被定义为一个数组。您可能有 2 个选项: 1 在 componentWillMount 中调用 getData,因此它将在调用您的渲染方法之前触发。或者,您可以将数据设置为空对象,并在尝试访问它之前检查 this.state.data 是否不等于 null。希望对您有所帮助。
    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2017-11-22
    • 2017-01-07
    • 2019-07-10
    • 2022-12-07
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多