如何在react-native

时间:2019-03-01 21:59:48

标签: react-native aws-amplify

我正在尝试显示我的react-native was-amplify移动应用程序中通过graphql获取的内容。我不知道如何将获取的数据传递给我的render方法。这是源代码。我需要能够显示render内部的singletour对象的内容。当我尝试在render方法中引用this.props.singletour时,React引发错误。我无法弄清楚的另一件事是如何将渲染内部导航接收的参数传递给GetTournament graphql查询。理想情况下,我希望ID:在GetTournament中包含navigation.getParam('itemId','NO-ID')而不是硬编码ID。再次,当我在异步方法调用内访问此参数时,react会引发错误……将不胜感激!

 class DetailsScreen extends React.Component {

 async componentDidMount() {
  try {
   const graphqldata = await API.graphql(graphqlOperation(GetTournament, { id: "4e00bfe4-6348-47e7-9231-a8b2e722c990" }))
  console.log('graphqldata:', graphqldata)
  this.setState({ singletour: graphqldata.data.getTournament })
  console.log('singletour:', this.state.singletour)
 } catch (err) {
   console.log('error: ', err)
  }
 }
render() {
/* 2. Get the param, provide a fallback value if not available */
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
return (
  <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
    <Text>Details Screen</Text>
    <Text>itemId: {JSON.stringify(itemId)}</Text>
    <Text>otherParam: {JSON.stringify(otherParam)}</Text>

    <Button
      title="Go to Home"
      onPress={() => this.props.navigation.navigate('Home')}
    />
    <Button
      title="Go back"
      onPress={() => this.props.navigation.goBack()}
    />
  </View>
  );
  }
 }

1 个答案:

答案 0 :(得分:0)

我想我知道您要做什么,并且可以通过重构代码来实现。

这就是我要做的:

  1. 在组件的constructor中捕获导航参数,并将其保存到state
  2. 为单游览状态设置初始值。为状态中的loaded设置一个值。 loaded值将使我们能够确定数据是否成功返回。
  3. 重构您的componentDidMount,使其使用现在存储在状态中的itemId
  4. 重构console.log来检查您是否已设置状态,因为状态未正确执行。
  5. render中,从state中提取值并处理数据是否为loaded。您可能希望显示一些加载屏幕,或者根本不想处理它。

这里是重构:

class DetailsScreen extends React.Component {
  constructor (props) {
    super(props);

    // capture the values that you have passed via your navigation in the constructor
    const { navigation } = props;
    const itemId = navigation.getParam('itemId', 'NO-ID');
    const otherParam = navigation.getParam('otherParam', 'some default value');

    this.state = {
      itemId: itemId,
      otherParam: otherParam,
      loaded: false,
      singletour: [] // you don't state what singletour is but you should set a default value here
    };
  }

  async componentDidMount () {
    try {
      // we can now use the state value for itemId as we captured it in the constructor of the component
      const graphqldata = await API.graphql(graphqlOperation(GetTournament, { id: this.state.itemId }));
      console.log('graphqldata:', graphqldata);

      // this is a bad way to access state after it has been set,
      // state is asynchronous and takes time to set.
      // You would need to access set by using the callback method
      // this.setState({ singletour: graphqldata.data.getTournament });
      // console.log('singletour:', this.state.singletour); // <- you should never do this after you setState

      // this is how you should access state after you have set it
      // this will guarantee that the state has been set before the
      // console.log is called, so it should show the correct value of state
      this.setState({
        singletour: graphqldata.data.getTournament,
        loaded: true // we are going to use the loaded value to handle our render
      }, () => console.log('singletour:', this.state.singletour));
    } catch (err) {
      console.log('error: ', err);
      // you may want to show an error message on the screen.
    }
  }
  render () {
    // access the passed parameters from state
    const { itemId, otherParam, loaded, singletour } = this.state;

    if (loaded) {
      // if once the data is loaded we can show screen
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>Details Screen</Text>
          <Text>itemId: {JSON.stringify(itemId)}</Text>
          <Text>otherParam: {JSON.stringify(otherParam)}</Text>
          <Text>singletour: {JSON.stringify(singletour)}</Text>

          <Button
            title="Go to Home"
            onPress={() => this.props.navigation.navigate('Home')}
          />
          <Button
            title="Go back"
            onPress={() => this.props.navigation.goBack()}
          />
        </View>
      );
    } else {
      // while we are waiting for the data to load we could show a placeholder screen
      // or we could show null. The choice is yours.
      return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
          <Text>Data not loaded</Text>
        </View>
      );
    }
  }
}

请注意,componentDidMount在第一次渲染发生后被调用,这就是为什么我们在loaded中拥有state值的原因。通过使用loaded,它可以使我们处理呈现给用户的内容,而不是呈现尚未完成数据加载的屏幕。

这显然是代码的一种可能重构。还有许多其他方法可以对其进行重构。

这里有一些很棒的关于设置状态的文章