Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 获取对象时,不会调用componentDidUpdate_Reactjs - Fatal编程技术网

Reactjs 获取对象时,不会调用componentDidUpdate

Reactjs 获取对象时,不会调用componentDidUpdate,reactjs,Reactjs,当状态更改时,不会激发componentDidUpdate 与用户界面差不多 用户输入图像标题值,然后上载图像。componentDidUpdate应该获取更新值 然后像这样相应地映射它 this.state.images.map( (img, i) => ( <Grid item sm={12} md={12} key={i} style={{ margin: '30px 0px'}}> <Paper>

当状态更改时,不会激发componentDidUpdate

与用户界面差不多

用户输入图像标题值,然后上载图像。componentDidUpdate应该获取更新值

然后像这样相应地映射它

this.state.images.map( (img, i) => (     
    <Grid item sm={12} md={12} key={i} style={{ margin: '30px 0px'}}>
            <Paper>
                <Typography variant="h6" align="center">{img.image_title}</Typography>
            <Image image_url={img.img_url} />    
        </Paper>                              
    </Grid>
))  
console.log(响应)


有一些关键问题可能会导致非常严重的bug:

  • 在init state上有
    images:{}
    (对象),之后在
    componentdiddupdate
    函数中尝试将其设置为数组:
    [this.state.image\u url,this.state.description,this.state.images]
    。不要这样做,这很令人困惑

  • 如果(this.state.image\u url!==prevState.image\u url)条件只有在您的
    Axios.post
    承诺成功解决时才会触发。你能分享一下console.log(响应)的结果吗?否则,它将永远不会被触发,至少基于这个代码段

更新: 我已经找到了真正的原因,为什么你看不到图像(或者你可能可以看到破碎的图像):

  • 上载功能应该扩展现有的图像数组。我稍微修改了Axios.post函数,只是为了能够在我这方面编译它,但你有一点:
  • 您使用每个
    组件diddupdate
    上包含3个项目的新数组来声明
    图像
    变量,这完全没有任何意义。你能解释一下你在这个生命周期中真正想要实现什么吗?因为您需要的一切都发生在
    handleUpload
    函数中(状态更新)

  • componentDidMount
    替换
    componentWillMount
    ,componentWillMount已弃用。这不是我想要的。ComponentWillMount从api中获取帖子非常好。我需要一些东西来更新文件上传时的状态。所以componentDidupdate是一个可行的解决方案,我只需要一个更好的逻辑。this.state.image\uURL登录componentDidMount是什么?这是新的图像URL还是旧的URL?我是说,
    componentWillMount
    已被弃用,我没有回答你的问题。我想我已经开始工作了,我会在一分钟后发布答案。好的,谢谢,几秒钟后会给你显示控制台。log(response)。你说不要这样做,因为它让人困惑,另一种方法是什么?设置为空数组
    images:[]
    ,因为
    render()
    方法中的此检查可能会使应用程序崩溃-
    this.state.images.length>0?(
    BTW,在示例图像中,您在单词sequelizenext中有一个输入错误:不要忘记将道具传递到构造函数超级函数:
    super(道具);
    import React, { Component } from "react";
    import Button from '@material-ui/core/Button';
    import TextField from '@material-ui/core/TextField';
    import Grid from '@material-ui/core/Grid';
    import Typography from '@material-ui/core/Typography';
    import Paper from '@material-ui/core/Paper';
    import ImageUploader from 'react-images-upload';
    import Axios from '../Axios';
    import Image from './Image';
    class Dashboard extends Component{
        constructor(props){
            super();
            this.state = {
                image_url: 'http://www.conservewildlifenj.org/images/artmax_1001.jpg', 
                images: {}, 
                description:'',
                upload:false,
            }
        }
        handleUpload =  file =>  {
            const data = new FormData()
            const image = file[0]
            console.log(this.state.description)
            // data.append('ourImage', this.state.description)
            data.append('ourImage',image, this.state.description )
            Axios.post('/images/upload', data).then((response) => {
                console.log(response);
                this.setState({
                    image_url:response.data.img_url,
                    description:response.data.image_title
                    // images: [...this.state.images, this.state.image_url ]
                })
            });
            this.props.history.push('/dashboard')
            console.log(this.state.image_url);
        }
        handleChange = (e) => {
            // e.preventDefault();
            this.setState({
                [e.target.name]: e.target.value
            })
            // console.log(this.state.description)
        }
        fileOnchange = (file) => {
            this.setState({
                [file[0].target.name]: file[0].target.value
            })
        }
        componentWillMount(){
            Axios.get('/images/uploads').then( (response) => {
                // let img;
                // let imgTitle;
                // Object.keys(response.data).forEach( (key) => {
                //     img = response.data[key].img_url
                //     imgTitle = response.data[key].image_title
                //     console.log(response.data);
                //     // console.log(key, img);
    
    
                //     console.log(this.state.images);
                // });
    
                this.setState({
                    images: response.data
                })
            })
    
    
        }
        componentDidUpdate(nextProps, prevState) {
            if (this.state.image_url !== prevState.image_url) {
                    console.log(nextProps.images); // doesnt fetch console log
                    console.log(prevState.images); // doesnt fetch console log
                    this.setState({
                        images: [ this.state.image_url, this.state.description, this.state.images]
                    });
            }
    
            // console.log(this.state.images); 
        }
        onUploadClick = (e) => {
            e.preventDefault();
            this.setState({
                upload: !this.state.upload
            })
        }
        render(){
            const uploader = ( 
                <ImageUploader
                    withIcon={true}
                    withPreview={true}
                    onChange={this.handleUpload}
                    singleImage={true}
                    buttonText='Upload an image'
                    imgExtension={['.jpg', '.gif', '.png', '.gif']}
                    maxFileSize={5242880}
                />
            )
            return(
                <div>
                <Grid container justify="center" spacing={16}>
                    <Grid item sm={8} md={6} style={{ margin: '40px 0px', padding: '0px 30px'}}>
                        <Typography align="center" variant="h6">
                            Welcome to the Dashboard
                        </Typography>
                            <Button onClick={this.onUploadClick} variant="outlined" component="span" color="primary">
                                {/* toggle between Upload or Close
                                    Will be upload by default, else if upload is clicked, close will show.
                                */}
                                {!this.state.upload ? "Upload": "Close"}
                            </Button>
                            {this.state.upload ? (
                                <div>
                                 <TextField
                                     id="outlined-name"
                                     label="Image Title"
                                     name="description"
                                     type="text"
                                     fullWidth
                                     style={{ borderRadius: '0px'}}
                                     className=""
                                     value={this.state.description}
                                     onChange={this.handleChange}
                                     margin="normal"
                                   />
                                    <br></br>
                                    <br></br>
                                  {uploader}
                                </div>
                            ):(
                                null
                            )}
                        {this.state.images.length > 0 ? (
                            this.state.images.map( (img, i) => (     
                                <Grid item sm={12} md={12} key={i} style={{ margin: '30px 0px'}}>
                                     <Paper>
                                         <Typography variant="h6" align="center">{img.image_title}</Typography>
                                        <Image image_url={img.img_url} />    
                                    </Paper>                              
                                </Grid>
                            ))
                        ) : (
                            <div>
                                <Grid item md={8}>
                                    <Typography>No Images yet</Typography>
                                </Grid>
                            </div>
                        )}
                    </Grid>
                    {/* Images  */}
                  </Grid>
                </div>
            )
        }
    }
    export default Dashboard;
    
    {
      "data": {
        "img_url": "http://res.cloudinary.com/dq281hpqd/image/upload/v1559943872/uploads/iobe6hc1qkfqxnyww8ki.png",
        "image_title": "foo",
        "id": 66
      },
      "status": 200,
      "statusText": "OK",
      "headers": {
        "content-type": "application/json; charset=utf-8",
        "content-length": "135"
      },
      "config": {
        "transformRequest": {},
        "transformResponse": {},
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "headers": {
          "Accept": "application/json",
          "Authorization": "eyJhbGciOiJIUzI1N***********sgNUmaIg"
        },
        "method": "post",
        "baseURL": "http://localhost:3000",
        "withCredentials": true,
        "url": "http://localhost:3000/images/upload",
        "data": {}
      },
      "request": {}
    }
    
    handleUpload =  file =>  {
        const data = new FormData()
        const image = file[0]
        console.log(this.state.description)
        // data.append('ourImage', this.state.description)
        data.append('ourImage',image, this.state.description )
    
        const axiosPost = new Promise(res => {
          setTimeout(() => res({
            data: {
              image_url: "newURL",
              image_title: "newTitle",
              description: 'a description'
            }
          }), 2000);
        });
    
        axiosPost.then(response => {
          const { image_url, description } = response.data;
          this.setState({
            image_url,
            description,
            images: [...this.state.images, response.data ]
          })
        });
        // this.props.history.push('/dashboard')
        console.log(this.state.image_url);
      }