如何将API请求的结果放入react native中的数组值中?

问题描述 投票:0回答:1

我在将我的本机应用程序中的API请求结果放入数组值时遇到问题。

这是被调用的函数

    export function getNewFilmFromApi(page) {
    return fetch(
    'https://api.themoviedb.org/3/discover/movie?api_key=' +
      API_TOKEN +
      '&release_date.gte=2019-10-01&release_date.lte=2019-12-31&language=fr&page=' +
      page,
  )
    .then(response => response.json())
    .catch(error => console.error(error));
}

这就是我试图将返回值放入数组的方式:

    const projects = [
  {
    title: getNewFilmFromApi().then(data => {
      return data.results[0].title;
    }),
    image: require('../Images/background.jpg'),
    author: 'Liu Yi',
    text: 'kkkk',
  },
  {
    title: 'The DM App - Ananoumous Chat',
    image: require('../Images/background.jpg'),
    author: 'Chad Goodman',
    text: 'kjhgfhjkl',
  },
  {
    title: 'Nikhiljay',
    image: require('../Images/background.jpg'),
    author: "Nikhil D'Souza",
    text: 'jjjjjj',
  },
];

我可以通过console.log看到data.results [0] .title有一个值,但是我不能将其放在数组中!

这是我尝试执行此操作时遇到的错误:

enter image description here

这是我的渲染函数,除了我要从API返回它的标题之外,其他所有东西都可以工作。

    render() {
    return (
      <Container>
        <AnimatedMask style={{opacity: this.state.opacity}} />
        <Animated.View
          style={{
            transform: [
              {translateX: this.state.pan.x},
              {translateY: this.state.pan.y},
            ],
          }}
          {...this._panResponder.panHandlers}>
          <Project
            title={projects[this.state.index].title}
            image={projects[this.state.index].image}
            author={projects[this.state.index].author}
            text={projects[this.state.index].text}
            canOpen={true}
          />
        </Animated.View>
        <Animated.View
          style={{
            position: 'absolute',
            top: 230,
            left: 0,
            zIndex: -1,
            width: '100%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            transform: [
              {scale: this.state.scale},
              {translateY: this.state.translateY},
            ],
          }}>
          <Project
            title={projects[getNextIndex(this.state.index)].title}
            image={projects[getNextIndex(this.state.index)].image}
            author={projects[getNextIndex(this.state.index)].author}
            text={projects[getNextIndex(this.state.index)].text}
          />
        </Animated.View>
        <Animated.View
          style={{
            position: 'absolute',
            top: 240,
            left: 0,
            zIndex: -2,
            width: '100%',
            height: '100%',
            justifyContent: 'center',
            alignItems: 'center',
            transform: [
              {scale: this.state.thirdScale},
              {translateY: this.state.thridTranslateY},
            ],
          }}>
          <Project
            title={projects[getNextIndex(this.state.index + 1)].title}
            image={projects[getNextIndex(this.state.index + 1)].image}
            author={projects[getNextIndex(this.state.index + 1)].author}
            text={projects[getNextIndex(this.state.index + 1)].text}
          />
        </Animated.View>
      </Container>
    );
  }
}

export default connect(mapStateToProps)(Card);

const Mask = styled.View`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.25);
  z-index: -3;
`;

const AnimatedMask = Animated.createAnimatedComponent(Mask);

const Container = styled.View`
  flex: 1;
  justify-content: center;
  align-items: center;
  background: #f0f3f5;
  margin-top: 80;
`;

const Text = styled.Text``;
var test;

const projects = [
  {
    title: getNewFilmFromApi().then(data => {
      return data.results[0].title;
    }),
    image: require('../Images/background.jpg'),
    author: 'Liu Yi',
    text: 'kkkk',
  },
  {
    title: 'The DM App - Ananoumous Chat',
    image: require('../Images/background.jpg'),
    author: 'Chad Goodman',
    text: 'kjhgfhjkl',
  },
  {
    title: 'Nikhiljay',
    image: require('../Images/background.jpg'),
    author: "Nikhil D'Souza",
    text: 'jjjjjj',
  },
];

您能提供任何解决方案以将值显示到数组中吗?

谢谢!

reactjs react-native redux react-redux react-native-android
1个回答
1
投票

您尝试用API调用的结果填充数组的方式将不起作用。

您的API调用是异步的,它返回Promise。因此,您必须等待API调用完成并等待Promise解析,然后在呈现组件时更新projects数组。

[我建议您将projects数组存储在一个状态中,并在首次渲染组件时进行API调用,如下面的简化示例所示:

function getNewFilmFromApi(page) {
  return fetch(`https://jsonplaceholder.typicode.com/todos/1`).then(res =>
    res.json()
  );
}

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

    this.state = {
      fetchError: false,
      isLoading: true,
      projects: [
        { title: null, author: `Liu Yi` },
        { title: `The DM App - Anonymous Chat`, author: `Chad Goodman` },
        { title: `Nikhiljay`, author: `Nikhil D'Souza` }
      ]
    };
  }

  componentDidMount() {
    const handleResponse = data => {
      const { title } = data;

      // assuming you just want to update
      // the first item in the `projects` array
      const nextProjects = [...this.state.projects];
      nextProjects[0].title = title;

      this.setState({
        projects: nextProjects,
        isLoading: false
      });
    };
    const handleError = err => {
      this.setState({
        apiError: true,
        isLoading: false
      });
    };

    getNewFilmFromApi()
      .then(handleResponse)
      .catch(handleError);
  }

  render() {
    const { apiError, isLoading, projects } = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }
    if (!isLoading && apiError) {
      return <p>Error loading projects</p>;
    }
    return <p>{JSON.stringify(projects)}</p>;
  }
}

这里是工作示例的链接:

© www.soinside.com 2019 - 2024. All rights reserved.