类组件中的SetState未运行(ReactJS)

pes8fvy9  于 2023-01-04  发布在  React
关注(0)|答案(2)|浏览(156)

我想通过一个特定的画廊图片的ID到它的详细信息页面,这是一个子组件的画廊。
为了达到这个目的,我调用了一个onClick函数"handleClick",当图像被选中时(这样键就作为新的属性传递给子组件)。
onClick函数为,但不会执行其中的setState。
状态不会改变,键(this. state. key)也不会作为新值(nextprop)传递给子组件。
下面是我的代码:

import io from 'socket.io-client';
import React, { Component } from "react";
import { GridList, GridListTile } from "@material-ui/core";
import ImageList from '@material-ui/core/ImageList'
import { Container } from 'react-bootstrap';
import { ImageListItem } from '@material-ui/core'
import { ImageListItemBar } from '@material-ui/core';
import ListSubheader from '@material-ui/core';
import IconButton from '@material-ui/core';
import InfoIcon from '@material-ui/core';
import styles from '../styles/ImageGallery.module.scss';
import Delete from '@mui/icons-material/Delete';
import FavoriteBorder from '@mui/icons-material/FavoriteBorder';
import { BrowserRouter as Router, Route, Switch, Link} from "react-router-dom";
import ItemDetail from "../pages/Items";

export default class IGallery extends React.Component {
    constructor(props) {
      super(props);    
/*       this.countryList = {
        key: 'test',
        name:'test'
      } */
      //this.handleClick = this.handleClick.bind(this);

      this.state = {
         countryList: [],
         wallet:'',
         key:''    }
     
      this.socket = io('http://localhost:3000')
      this.socket.on('new_data', (value) => this.handleMessage(value));
   
      this.socket.on('disconnect', function(){
      this.socket.disconnect();
    });
     
    }

    handleMessage(value) {

   
       let imageDataSet=(JSON.parse(value).new_val);
       console.log("New Data "+value['new_val']);
       //let imageDataSet = value2.new_val;
       console.log("Test "+imageDataSet);
       //console.log("Test "+imageDataSet.id);
      this.setState({
          countryList: [ ...this.state.countryList, {key:imageDataSet.id, image:imageDataSet.image}, ],
      }) 
    
    }

    handleClick = (_key) => {
        console.log("Key of Gallery Image "+_key);
        console.log('before setState', this.state.key)
        this.setState({key:_key}, console.log('after setState', this.state.key));
  
      
    }

    render()
    {

    return (

        <div className={styles.gallery}><h1>Gallery</h1>
         
    
    <ImageList cols={6} rowHeight={320}>
        {this.state.countryList.map((data, idx) => (
         <ImageListItem  key={idx} className={styles.imageItem}>
           <Link to="/item" onClick={() => this.handleClick(data.key)}>
            <img src={data.image}  width={320} /><ItemDetail key={this.state.key}></ItemDetail> 
           </Link>
          </ImageListItem >
        ))}
      </ImageList >
     
        </div>
      );
    }
    
  }

我希望控制台日志显示新的状态。

this.setState({key:_key}, console.log('after setState', this.state.key));
u1ehiz5o

u1ehiz5o1#

来自setState()文档
setState()的第二个参数是可选的回调函数,它将在setState完成并重新呈现组件后执行。
因此必须传递一个回调(而不是直接调用console.log

this.setState({key:_key}, () => console.log('after setState', this.state.key));
lymnna71

lymnna712#

setState异步工作,您无法在设置后立即获得其值,这将需要一些时间。
要了解是否设置了state,请使用具有state依赖项的useEffect

useEffect(()
  {console.log(this.state.key)} 
   // If you want to navigate to Details page once key is set 
   ..... 👈  Navigate to Details Screen with prop of key here
,[this.state.key]); 👈 Add your dependency state here

相关问题