【问题标题】:React - Load JSON and render componentReact - 加载 JSON 并渲染组件
【发布时间】:2017-07-14 00:41:07
【问题描述】:

正如标题所说,我正在尝试渲染一个 React 组件,其中包含我通过使用 fetch() 加载从 JSON 中获取的数据。

api 调用工作正常,但我无法呈现数据。

代码如下:

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

        this.state = {
            user: {}
        }
    }

    getUserById(uId) {
        fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
            .then( (response) => {
                return response.json()
            })
            .then( (json) => {
                return json;
            });
    }

    componentDidMount() {
        this.setState({
            user: this.getUserById(4)
        })
    }

    render() {
        return (
            <div>
                <h1>User</h1>
                <p>ID: {this.state.user.id}</p>
            </div>
        );
    }
}

ReactDOM.render(
    <App/>,
    document.getElementById("container")
);
<div id="container"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

有解决这个问题的想法吗?

【问题讨论】:

    标签: javascript json ajax reactjs ecmascript-6


    【解决方案1】:

    问题出在这一行:

    <div class="container"></div>
    

    您定义了class 并通过getElementById 获取它。

    另一个变化是,ajax 调用将是异步的,因此getUserById 不会立即返回数据,setState 将在状态变量中设置undefined 值而不是从服务器返回的数据。要解决此问题,请在收到回复后发送setState

    检查一下:

    class App extends React.Component {
        constructor(props) {
            super(props);
    
            this.state = {
                user: {}
            }
        }
    
        getUserById(uId){
            fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
            .then( (response) => {
                return response.json()
            })
            .then( (json) => {
                this.setState({
                    user: json
                })
            });
        }
    
        componentDidMount() {
            this.getUserById(4);
        }
    
        render() {
            console.log(this.state.user);
            return (
                <div>
                    <h1>User</h1>
                    <p>ID: hello</p>
                </div>
            );
        }
    }
    
    ReactDOM.render(
        <App/>,
        document.getElementById("container")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="container"></div>

    注意:您正在进行ajax 调用,因此不要在 setState 中调用函数,而是在收到响应后在 .then 中执行 setState,如下所示:

    .then(json => {
        this.setState({user: json});
     });
    

    【讨论】:

    • 呵呵,是的。我在sn-p中搞砸了。笔记解决了我的问题,谢谢!
    【解决方案2】:

    尝试将 getUserById 方法和 setState 绑定到您的用户对象与 json 响应中。

    class App extends React.Component {
    constructor(props) {
        super(props);
    
        this.state = {
            user: {}
        }
    this.getUserById = this.getUserById.bind(this); //add this to your constructor
    }
    
    getUserById(uId) {
        fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
            .then( (response) => {
                return response.json()
            })
            .then( (json) => {
                return json; //setState in here with your ajax request**strong text**
            });
    }
    
    componentDidMount() {
        this.setState({
            user: this.getUserById(4)
        })
    }
    
    render() {
        return (
            <div>
                <h1>User</h1>
                <p>ID: {this.state.user.id}</p>
            </div>
        );
    }
    }
    
    ReactDOM.render(
    <App/>,
    document.getElementById("container")
    

    【讨论】:

      【解决方案3】:

      我认为您的主要问题是 getUserById 方法不返回任何内容,您应该在其中设置状态。那么你给主容器的id有问题,但我想你只在sn-p中犯了一个错误。

      上面的代码我已经测试过了,试试看:

      class App extends React.Component {
          constructor(props) {
              super(props);
      
              this.state = {
                  user: null
              }
          }
      
          getUserById(uId) {
              fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
                  .then( (response) => {
                      return response.json()
                  })
                  .then( (json) => {
                      return json;
                  })
                  .then((result) => {
                    this.setState({user: result});
                  });
          }
      
          componentDidMount() {
              this.getUserById(4)
          }
      
          render() {
              console.log(this.state.user);
              return (
                  <div>
                      <h1>User</h1>
                      <p>{this.state.user != null ? this.state.user.id : 0}</p>
                  </div>
              );
          }
      }
      
      ReactDOM.render(
          <App/>,
          document.getElementById("container")
      );
      

      【讨论】:

        【解决方案4】:

        我可以看到的问题 - 你的 fetch promise 不会返回从服务器获得的数据,所以我的建议是在你的 promise 回调中设置 setState,所以它应该看起来像:

        getUserById(uId) {
            fetch(`https://jsonplaceholder.typicode.com/users/${uId}`)
                .then(result => result.json())
                .then(json => {
                    this.setState({user: json});
                });
        }
        componentDidMount() {
            this.getUserById(4);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-05-26
          • 2016-11-23
          • 1970-01-01
          • 1970-01-01
          • 2020-12-12
          • 2018-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多