TypeScript React setState is not working
Clash Royale CLAN TAG#URR8PPP
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(?=(d3)+(?!d))/g, ',')
parser=(,*)/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.
There are no compiler errors and everythings seems to be ok with types.
What am I missing in here?
InputNumber
this.setState
Your
getDerivedStateFromProps
method is called every time the state changes, and it is overwriting the state from the props. What were you trying to achieve?– Matt McCutchen
Aug 10 at 9:56
getDerivedStateFromProps
@ImeshChandrasiri yup
– Hayk Safaryan
Aug 10 at 10:01
@MattMcCutchen I want to pass
onConfirm
function as a prop then on button click pass the state value to it. The component gets its initial value from the props as well.– Hayk Safaryan
Aug 10 at 10:02
onConfirm
What should happen if the number in the state has been changed and then the number in the props changes? Do you reset the state? The answer to this will determine what you need to write in the
getDerivedStateFromProps
method.– Matt McCutchen
Aug 10 at 10:05
getDerivedStateFromProps
1 Answer
1
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. This should hopefully work (not tested):
getDerivedStateFromProps
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 : )
// ...
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use the setstate callback function to print the console object to see whether the object is updated.
– Imesh Chandrasiri
Aug 10 at 9:54