代码之家  ›  专栏  ›  技术社区  ›  Olalekan

ReactJS:将状态值设置为数组的正确方法是什么?

  •  2
  • Olalekan  · 技术社区  · 7 年前

    class Admin extends Component {
    
    
        componentDidMount () {
    
            var that = this;
            fetch('http://localhost:4500/data/users', {
                method: 'GET',
                headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                }
             }).then(function(response) {
                 return response.json();
            }).then(function(json){
                 console.log(json);
                 that.state = {users: json};
            });
    
        }
    
        render() {
    
         return (
    
            <SpicyDatatable
              tableKey={key}
              columns={columns}
              rows={this.state.users}
              config={customOptions}
            />
           );
        }
    }
    

    将状态值设置为数组并进行渲染的正确方法是什么?谢谢

    3 回复  |  直到 7 年前
        1
  •  3
  •   abdul    7 年前

    首先在构造函数中初始化状态,如下所示

    constructor(props) {
            super(props);
            this.state = {users : []} //initialize as array
        }
    

    that.state = {users: json}; 使用设置状态

    that.setState({ users: json });
    
        2
  •  1
  •   Paul Fitzgerald    7 年前

    你应该使用React setState() 方法

    that.setState({ users: json });
    
        3
  •  0
  •   jonahe    7 年前

    setState({ users: json }) ,这是对的。

    abul 也就是说,您还可以根据组件状态进行条件渲染。一、 e如果用户尚未加载,则可以渲染不同的组件。

    render() {
       const users = this.state.users;
       return !users ?
          <p>Loading..</p> : 
          <YourComponent users={users} />;
    }