首页 > 解决方案 > setState 在 handleClick 中不起作用

问题描述

我的 setState 不会影响 handleClick 事件处理程序中的状态。我确定 handleClick 有效,因为它记录了参数。
我对 React 有点陌生,所以我必须忽略一些东西。这是否意味着我的 handleClick 函数有问题?

任何建议将不胜感激!

    import React from 'react';
    import './Projects.css';
    import Footer from '../../Components/Footer/Footer.js';
    import ProjectPage from 
      '../../Components/ProjectPage/ProjectPage.js';
    import { Redirect, Link } from 'react-router-dom';

    class Projects extends React.Component {
      constructor(props) {
        super(props);
        this.state= {
          title: "kaufmann house",
          content: "charles",
        }
        this.getImages = this.getImages.bind(this);
      }

      getImages() {
        var VisibilitySensor = require('react-visibility-sensor');
        return this.props.projectList.map((post,index) =>
       <div>
          <div className="projects">
            <VisibilitySensor onChange={isVisible => 
              this._onChange(isVisible, post.title)}>
              <img key={post.id} src={post.featureImage} 
                className='projectImage' alt='projectImage' onClick= . 
                {this.handleClick.bind(this, post.content)}/>
            </VisibilitySensor>
          </div>
        </div>
        )
      }

      _onChange = (isVisible, param) => {
        isVisible && this.setState({title: param});
      };

      handleClick = (param) => {
        console.log(param);
        this.setState({content: param});
      };

      render() {

        return (
           <div>
            <Link to={{pathname: `/ProjectPage/${this.state.title}`,
                state: {
                  info: `${this.state.content}`}
                }}>{this.getImages()}</Link>
            <Link to={{pathname: `/ProjectPage/${this.state.title}`,
                state: {
                  info: `${this.state.content}`}
                }}>
              <Footer title={this.state.title}/>
             </Link>
          </div>
        )
       }
    }



    export default Projects;

标签: reactjssetstate

解决方案


   this.state= {
      title: "kaufmann house",
      content: "charles",
    }

您的state包含标题和内容。你必须setState喜欢下面。否则,您的 newstate将无法正确更新,因为您替换了整个state对象。

  _onChange = (isVisible, param) => {
    isVisible && this.setState({
       ...this.state,
       title: param
     });
  };

  handleClick = (param) => {
    console.log(param);
    this.setState({ 
       ...this.state,
       content: param
    });
  };

推荐阅读