简体   繁体   English

this.setState无法正常工作

[英]this.setState is not working correctly

I am using React 16 with Redux and i am using this.setState func onClick. 我正在将React 16与Redux一起使用,并且正在使用this.setState func onClick。 But it is not working correctly. 但是它不能正常工作。 I tried to debug for hours and could not find any solution. 我尝试调试了几个小时,却找不到任何解决方案。 Here is my code; 这是我的代码;

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class SSelect extends Component {
    state = {
        selectedName: '',
    }

    handleSelect = (id, name) => {
        this.setState({ selectedName: name });
        this.props.handleSelect(id); // this is redux action
    }

    render() {
        console.log(this.state.selectedName);
        return (
            <div>
                {
                    this.props.options.map(option => (
                        <div
                            key={option.id}
                            role="button"
                            onKeyPress={() => this.handleSelect(option.id, option.name)}
                            onClick={() => this.handleSelect(option.id, option.name)}
                            tabIndex="0"
                        >
                            {option.name}
                        </div>
                    ))
                }
            </div>
        );
    }
}

SSelect.propTypes = {
    handleSelect: PropTypes.func.isRequired,
    options: PropTypes.array.isRequired,
    segmentIndex: PropTypes.number,
};

SSelect.defaultProps = {
    segmentIndex: 0,
};

export default onClickOutside(SSelect);

console.log(this.state.selectedName); prints nothing, if i select same option on list, it prints true result. 什么都不打印,如果我在列表上选择相同的选项,则打印真实结果。 After select a new option, it prints empty again. 选择新选项后,它将再次打印为空。

when i track my redux processes, i saw that it is working and sets new value to store correctly. 当我跟踪我的redux进程时,我看到它正在工作,并设置了新值以正确存储。 when i remove my redux action, console.log(this.state.selectedName); 当我删除我的redux操作时, console.log(this.state.selectedName); printing true value. 印刷真实价值。

here is my react and redux versions; 这是我的react和redux版本;

"react": "^16.2.0",
"react-redux": "^5.0.6",
"redux": "^3.7.2",

Thank you for your help. 谢谢您的帮助。

To solve this problem a simple way, You can set the selectedName manually and then you can do force update. 要以简单的方式解决此问题,可以手动设置selectedName ,然后进行强制更新。

handleSelect(id, name) {
this.state.selectedName=name;
this.forceUpdate();
this.props.handleSelect(id);
}

To redux setState 还原setState
handleSelect(id,name){ this.setState({ selectedName: name }) };

onClick={this.handleSelect.bind(this,option.id, option.name)}

Unless my eyes are deceiving me, you have defined handleSelect as a class method and not an instance method meaning the this inside of the handleSelect function you have defined does not refer to your component. 除非我的眼睛在欺骗我,否则您将handleSelect定义为类方法,而不是实例方法, this意味着您定义的handleSelect函数内部的this并不引用您的组件。

You should define it as: 您应该将其定义为:

handleSelect(id, name) {
    this.setState({ selectedName: name });
    this.props.handleSelect(id); // this is redux action
}

rather than: 而不是:

handleSelect = (id, name) => {
    this.setState({ selectedName: name });
    this.props.handleSelect(id); // this is redux action
}

I suppose you wrap the component with connect() ? 我想您用connect()包装了组件?

As far is I know connect() makes you component pure (in redux terminology - props only) by default. 据我所知,默认情况下connect()使您的组件pure (在redux术语中-仅支持props)。 It can be overridden in the fourth options argument of connect . 可以在connect的第四个options参数中覆盖它。

However most likely the best solution would be to get rid of internal state, because that's what we use redux for 但是,最好的解决方案很可能是摆脱内部状态,因为这就是我们使用redux的目的

[options] (Object) If specified, further customizes the behavior of the connector. [选项](对象)如果指定,则进一步自定义连接器的行为。 In addition to the options passable to connectAdvanced() (see those below), connect() accepts these additional options: 除了connectAdvanced()可以通过的选项(请参阅下文)之外,connect()接受以下其他选项:

[pure] (Boolean): If true, connect() will avoid re-renders and calls to mapStateToProps, mapDispatchToProps, and mergeProps if the relevant state/props objects remain equal based on their respective equality checks. [pure](布尔值):如果为true,则connect()将避免重新渲染并在相关状态/道具对象根据其各自的相等性检查保持相等的情况下调用mapStateToProps,mapDispatchToProps和mergeProps。 Assumes that the wrapped component is a “pure” component and does not rely on any input or state other than its props and the selected Redux store's state. 假定包装的组件是“纯”组件,除了其道具和所选Redux存储的状态外,不依赖于任何输入或状态。 Default value: true 默认值:true

https://github.com/reactjs/react-redux/blob/master/docs/api.md https://github.com/reactjs/react-redux/blob/master/docs/api.md

This is very strange but i solved the problem. 这很奇怪,但我解决了问题。

On my reducer, my key's name was segment . 在我的减速器上,我的键名是segment I converted the name to selectedSegment and problem solved. 我将名称转换为selectedSegment并解决了问题。 I think segment word is reserved but i could not find any doc about reserved words. 我认为segment字是保留字,但我找不到有关保留字的任何文档。

I will open an issue to react-redux 我将对React-redux提出一个问题

Thank you all 谢谢你们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM