简体   繁体   English

TypeScript React setState不起作用

[英]TypeScript React setState is not working

I have a component with input like this 我有这样的输入组件

import * as React from 'react'

import { InputNumber, Button } from 'antd'

interface IProps {
  value: number
}

interface IState {
  value: number
}

class ConfirmInput extends React.Component<IProps, IState> {
  public readonly state = {
    value: 0
  }

  static getDerivedStateFromProps = ({ value }: IProps) => ({ value })

  public render () {
    return (
      <div>
        <InputNumber
          value={this.state.value}
          formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
          parser={(value): any => value && value.replace(/\$\s?|(,*)/g, '')}
          onChange={(value: number) => {
            console.log('value', value)
            this.setState({ value })
          }}
        />
        <Button
          onClick={() => console.log('this.state.value', this.state.value)}
          type="primary"
        >
          Bid
        </Button>
      </div>
    )
  }
}

export default ConfirmInput

on the InputNumber I have on change and that gets a number as a value, however this.setState doesn't change the value. 在我更改的InputNumber上,它将获取一个数字作为值,但是this.setState不会更改该值。 There are no compiler errors and everythings seems to be ok with types. 没有编译器错误,并且一切似乎都可以使用类型。 What am I missing in here? 我在这里想念什么?

You'll need to store the original value in the state so that your getDerivedStateFromProps implementation can overwrite the current value only when the prop changes. 您需要将原始值存储在状态中,以便您的getDerivedStateFromProps实现仅在prop更改时才能覆盖当前值。 This should hopefully work (not tested): 希望这可以正常工作(未经测试):

interface IState {
  value: number
  origValue: number
}

class ConfirmInput extends React.Component<IProps, IState> {
  // ...
  static getDerivedStateFromProps = (props: IProps, state: IState) =>
    (props.value != state.origValue ? { origValue: props.value, value: props.value } : {})
  // ...
}

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

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