如何将数据传递给 react-native 中的 render 方法

How to pass data to the render method in react-native

我正在尝试在我的 react-native was-amplify 移动应用程序中显示通过 graphql 获取的内容。我不知道如何将获取的数据传递给我的渲染方法。这是源代码。我需要能够在渲染中显示 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. 在组件的 constructor 中捕获导航参数并将它们保存到 state
  2. 为状态中的singleTour设置一个初始值。在状态中为 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 在第一次渲染发生后被调用,这就是我们在 state 中具有 loaded 值的原因。通过使用 loaded,它允许我们处理呈现给用户的内容,而不是呈现数据尚未完成加载的屏幕。

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

这里有一些关于设置状态的精彩文章