使用fetch进行React-native数组数据赋值

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

我正在开发一个作为初学者的反应动作的移动应用程序。使用react-native时我遇到了一些问题。让我详细解释一下,我想要做的是从Restful api获取数据并将这些数据分配给反应中的数组。下面是我填写数组数据的代码。

function getMoviesFromApiAsync() {
 return fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
.then((responseJson) => {
  return JSON.stringify(responseJson)
})
.catch((error) => {
  console.error(error);
});
}
const initialState = {
 data: getMoviesFromApiAsync();
  };

export default (state = initialState,action ) => {
  return state;
};

以上是我的所有.Js文件,它没有类声明。

任何帮助?

javascript arrays reactjs react-native fetch-api
2个回答
1
投票

您可以创建一个类组件,其初始状态为data为空数组,然后在data钩子中获取真正的componentDidMount并将其置于状态。

function getMoviesFromApiAsync() {
  return fetch("http://localhost:8080/JweSecurityExample/rest/security/retrieveItems")
    .then(response => response.json())
    .catch(error => {
      console.error(error);
    });
}

class App extends React.Component {
  state = {
    data: []
  };

  componentDidMount() {
    getMoviesFromApiAsync().then(data => {
      this.setState({ data });
    });
  }

  render() {
    return <div>{JSON.stringify(this.state.data)}</div>;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.