React.useState Hook 只显示对象的长度,不显示对象本身

React.useState Hook only displaying length of object, not object itself

基本上,我有一个名为上传的组件:

const Upload = () => {
    const [scene , setScene] = React.useState([]);

    // handleUpload = (event) => {
    //     console.log('Success!');
    // }


    function renderHandler(s){
      console.log('[RENDER] calling...')
      console.log(s);

      if(scene.length == 0){
        console.log('[RENDER] Denied!')
        return(
          <div>
            Nothing is rendered..
          </div>
        )
      } else {
        console.log('[RENDER] Working...')
        console.log('[RENDER] Received planes:');
        console.log(blockState);
        console.log(scene);

        return (
          <View top={blockState}/>
        )
      }
    }

    function parseNBT(input) {
      setScene(scene.push('1'));
      setScene(scene.push('2'));
      console.log('scene:');
      console.log(typeof scene);
      console.log(scene);
      console.log('\n+blockState:');
      console.log(typeof blockState);
      console.log(blockState)



    }
     return (
    <Container>
    Input NBT file <br/>
    <input type="file" onChange={handleChange}></input>
    {renderHandler(scene)}
    </Container>
  )
}

这里的问题是,当我在 parseNBT 和控制台日志场景中设置场景状态时,它给了我数组:

然而,当我从 renderHandler 调用它时,它只是 returns 数组的长度,在本例中是 2

很奇怪,也许我漏掉了什么?

.pushreturns数组的长度。

Return value
The new length property of the object upon which the method was called.


尝试

  setScene( currentScene => [...currentScene, '1'] );
  setScene( currentScene => [...currentScene, '2'] );

简而言之,您将 'scene' 视为可变对象,而它是不可变的。意思是,当您尝试执行 'scene.push' 时,它正在尝试修改不可变对象。常规数组是可变的,但不是反应状态数组。因此,你不想直接更新场景,你想获取它以前的状态,将它与你想要的新值连接起来,然后让这个新值成为你的新状态。

像这样:

替换你的台词:

  setScene(scene.push('1'));
  setScene(scene.push('2'));

与:

 setScene((scene) => [...scene, 1]);
 setScene((scene) => [...scene, 2]);