【问题标题】:React-native array data assignment with fetch使用 fetch 进行 React-native 数组数据分配
【发布时间】:2019-07-16 10:35:00
【问题描述】:

作为初学者,我正在用 react-native 开发一个移动应用程序。我在使用 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


    【解决方案1】:

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

    示例

    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>;
      }
    }
    

    【讨论】:

    • @eccck 好的。如果您无法弄清楚,请考虑提出另一个问题。
    • 其实不用再问了,我只需要在类声明之外获取数据变量,但我还没想好怎么做。 @tholle
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 2020-09-08
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多