【问题标题】:How to put data from json response in an array in reactjs如何将来自json响应的数据放入reactjs中的数组中
【发布时间】:2021-08-01 17:44:01
【问题描述】:

我试图显示数据库中的图像并用地图循环浏览它们。代码如下:

class Container extends React.Component
{
   
    state ={
        userData:[]
      }
    
    
     
    fethData= async()=>{
      fetch("http://localhost:5000/user") // could be any rest get url
      .then(response => response.json())
      .then(result =>
        this.setState({
          userData: result
         
        })
      );
    }
 
    
    
    componentDidMount() {
       this.fethData();
       
       alert(this.state.userData);
     
        $(function(){  
            //Make every clone image unique.  
              var counts = [0];
               var resizeOpts = { 
                 handles: "all" ,autoHide:true
               };    
              $(".dragImg").draggable({
                                    helper: "clone",
                                    //Create counter
                                    start: function() { counts[0]++; }
                                   });
           
           $("#dropHere").droppable({
                  drop: function(e, ui){
                          if(ui.draggable.hasClass("dragImg")) {
                $(this).append($(ui.helper).clone());
              //Pointing to the dragImg class in dropHere and add new class.
                    $("#dropHere .dragImg").addClass("item-"+counts[0]);
                       $("#dropHere .img").addClass("imgSize-"+counts[0]);
                           
              //Remove the current class (ui-draggable and dragImg)
                    $("#dropHere .item-"+counts[0]).removeClass("dragImg ui-draggable ui-draggable-dragging");
           
           $(".item-"+counts[0]).dblclick(function() {
           $(this).remove();
           });     
               make_draggable($(".item-"+counts[0])); 
                 $(".imgSize-"+counts[0]).resizable(resizeOpts);     
                  }
           
                  }
                 });
           
           
           var zIndex = 0;
           function make_draggable(elements)
           {    
               elements.draggable({
                   containment:'parent',
                   start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
                   stop:function(e,ui){
                   }
               });
           }    
           
           
               
              });
    }
    
    

    changeColor(params) {
        this.setState({
            color: params.target.value
        })
    }

    changeSize(params) {
        this.setState({
            size: params.target.value
        })
    }
    
    render() {
      
        return (
            
                    <div className="container">
                        <div className="tools-section">
                            <div className="color-picker-container">
                                Select Brush Color : &nbsp; 
                                <input type="color" value={this.state.color} onChange={this.changeColor.bind(this)}/>
                            </div>

                            <div className="brushsize-container">
                                Select Brush Size : &nbsp; 
                                <select value={this.state.size} onChange={this.changeSize.bind(this)}>
                                    <option> 5 </option>
                                    <option> 10 </option>
                                    <option> 15 </option>
                                    <option> 20 </option>
                                    <option> 25 </option>
                                    <option> 30 </option>
                                </select>
                            </div>

                        </div>
                
                        <div className="board-container">
                            
                            
                        
                            <h4>Select picture!</h4>
                        
                                
                                   
                              
                         
                                    
                                           
                                            {this.state.userData.map((data) => (
                                            
                                            <div class="dragImg">
                                                
                                                  
                                                 <img src={data.picture} class="img"/> // column data received
                                               
                                                
                                              </div>
                                            ))}
                             
                                   
                                
                    
                        
                        
                            <div  id="dropHere">
                                
                            <Board color={this.state.color} size={this.state.size}></Board></div>
                            
                        </div>
                    
                    </div>
           
        );
    }

    
}



export default Container

我想将 fethData 函数中的数据放入 userData 数组。但是,当我运行该网站时,我会收到一条提示用户数据未定义的警报。为什么没有向 userData 添加任何内容?

这是从数据库中获取的json数据:

[{"idpictures":1,"picture":"images/kitten.jpg","title_picture":"Cat"},{"idpictures":2,"picture":"images/puppy.jpg","title_picture":"Dog"}]

我希望这样存储数据:

userData:[{idpictures:1,picture:"images/kitten.jpg",title_picture:"Cat"}]

伙计们,我解决了。这是我对代码所做的更改:

constructor(){
     super();
      this.state ={
          userData:[]
        }
    }
    
  
    
    
    async componentDidMount() {
      const url = "http://localhost:5000/user";
      const response = await fetch(url);
      const data = await response.json(); 
      this.setState({userData: data});
      console.log(this.state.userData);
       
       if (this.state.userData) {alert(this.state.userData)}



【问题讨论】:

  • Why is nothing added to userData? 很可能是因为在组件挂载之前未完成获取。
  • 当我放 JSON.parse 时它仍然告诉我 undefined
  • @MikaelsSlava 我怎样才能让它在安装之前完成?
  • 嗯,这很棘手。我将获取父组件并使用包含所述数据的道具安装该组件。或者,如果您不需要在组件挂载后保存数据,只需使用 componentDidUpdate 并将警报包装在 if 语句中 if (this.state.userData) {alert(this.state.userData)}
  • @MikaelsSlava 嗯现在仍然无法正常工作,它给了我空警报

标签: node.js json reactjs fetch


【解决方案1】:

ReactJS 与 Vue 不同,使用:this.state.userData 访问 userData。而fetchData是一个异步函数,你不能同步得到它的结果。

【讨论】:

  • 出于某种原因,当我这样做 this.state.userData: JSON.parse(result) 时,它在这行中给了我三个错误,上面写着 ':' 和 ',' 预期
  • 这是什么this.state.userData: JSON.parse(result)?你写的this.setState函数没问题。获取状态的方式不是
  • this.state.userData: JSON.parse(result) 是我在 setstate 中编写的,用于将 json 放入 userData 数组中
  • 保持原样(在问题中)。在警报中将其从 this.userData 更改为 this.state.userData
  • @MikaelsSlava 嗯仍然给我一个空警报。我做了控制台日志并说它的 Array(0) 里面什么都没有
【解决方案2】:

这是工作示例

  fethData= ()=>{
    return new Promise((resolve, reject)=>{

     fetch("http://localhost:5000/user") // could be any rest get url
     .then(response => response.json())
     .then(result =>
       this.setState({userData: result},()=>{
           resolve();
       })
     );
    })
   }

  async componentDidMount(){
    await this.fetchData();
    alert(this.state.userData);
  }

【讨论】:

    【解决方案3】:

    您应该在构造函数中定义组件的状态。此外,JS 中的所有数据获取都是异步的。请注意您编写的 fetch 函数中的 .then。它包含响应返回后将执行的代码。

    class Container extends React.Component
    {
       constructor(props) {
         super(props)
         this.state ={
           userData:[]
        }
       }
        
        fethData = async() => {
          fetch("http://localhost:5000/user") // could be any rest get url
          .then(response => response.json()) // you might not need this, depends on the response
          .then(result =>
            this.setState({
              userData: result
             
            })
          );
        }
     
        componentDidUpdate() {
           alert(this.state) // This should show your data (when it gets here)
        }
        
        componentDidMount() {
           this.fethData();
           
           alert(this.state.userData); // this will fire before the response from localhost:5000/user gets here
        }
            
    }
    export default Container
    

    【讨论】:

      猜你喜欢
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 2017-11-03
      • 1970-01-01
      • 2015-05-13
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多