0

I just try to use react hook recently.

If I extends Componet, I declare my state like this:

  constructor(props) {
    super(props);

    // dummy state
    this.state = {
      focus: false
      name: 'test'
      image: ''
      avatarSource: '',
      imageBase: 'sfsafsfasf',
      imageLoader: null,
    }

If I want to send all of the state values, I will use ...this.state

just like:

sendStateFunction(...this.state);

If I use react hook, I declare my state like this:

const test = () => {

  const [name, setName] = useState('');
  const [image, setImage] = useState('');
  const [sex, setSex] = useState(0); 
  const [id, setId] = useState('');
}

But I have no idea how to send all of the state values just use one line code:

sendStateFunction();  // What should I type the arguments ?

1 Answer 1

2

React let you define state object with multiple subvalues with hooks like that :

function DummyComponent(){
const [state, setState] = useState({ focus: false,
    name: 'test',
    image: '',
    avatarSource: '',
    imageBase: 'sfsafsfasf',
    imageLoader: null,})
// You can update it like that:
return <Button onClick={()=>setState(prevState=>{return {...prevState, newKey:1}})}>Click</Button>
}

Or you can use a reducer using the hook useReducer. All of those issues are stated in React hooks Documentation

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. So I can use just like ...state in your example right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.