【问题标题】:The difference between using useState with [] and without it, and also with {}使用带有 [] 和不使用 useState 以及使用 {} 的区别
【发布时间】:2021-02-26 13:54:41
【问题描述】:

大家好,我有两个关于 react.js 钩子的问题。请帮忙。迷茫了几天:(
1.useState()中使用[]和不使用[]有什么区别
我注意到当使用 useState([]) 时,console.log(array) 会像

(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

但是,当我在代码中使用 useState() 时,它将如下所示,并且我无法使用 array.length 会出现错误提示 “无法读取未定义的属性长度”

Array(100)
0: {id: "181913649", name: "Drake Hotline Bling", url: "https://i.imgflip.com/30b1gx.jpg", width: 1200, height: 1200, …}
1: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip.com/1ur9b0.jpg", width: 1200, height: 800, …}
2: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip.com/1...
.
.

2.另外,我们什么时候在 useState({}) 中使用 {} ?我知道 {} 是对象。请举一些例子:(

以下是App.js的主要代码:

function App() {
  const [array,setarray]=useState([])

  useEffect(()=>{
    fetch("https://api.imgflip.com/get_memes")
      .then(response => response.json())
      .then(response => {
          const {memes} = response.data
          console.log(memes[0].url)

          setarray(memes)
          
      })
  },[])
  console.log(array)
  console.log(array[0])
  console.log(array.length)
  
  return (
    <div>
      <Header />
      <Control data={array}/>
    </div>
  );
}

export default App;

【问题讨论】:

  • useState 函数是一个 React 钩子,它的参数设置创建状态的初始值。如果你传递一个数组,它将是一个数组,如果你传递一个对象,它将是一个对象,等等。如果你不传递任何东西,那么将使用undefined
  • console.log 的输出几乎无关紧要。您传递给useState 的参数是初始值。使用哪个值取决于您希望状态具有哪个值,以及其他代码期望该值是什么。我假设memes 是一个数组,因此将其初始化为一个空数组似乎是正确的。还要查看Control 期望为data 获得什么价值。

标签: javascript reactjs ecmascript-6 react-hooks


【解决方案1】:

如果您在不传递参数的情况下调用useState(),则状态变量(array)的初始值将是undefined。尝试读取array 的属性length(即array.length)会报错:

const [array, setArray] = useState()

console.log(array) //=> undefined
console.log(array.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined

如果您调用useState([]),即传递一个空数组作为参数,状态变量(array)的初始值将是一个空数组([])。尝试读取array 的属性length(即array.length)将正常工作:

const [array, setArray] = useState([])

console.log(array) //=> []
console.log(array.length) //=> 0

如果您稍后要将array 设置为一个数组——而您是在useEffect() 中——最好将初始值设置为一个空数组。然后您可以安全地将array 视为一个数组,即您不必检查它是undefined 还是数组。

同样,如果您的状态稍后将成为一个对象,您可能希望使用{} 作为初始值。这对于防止错误很有用。例如:

const [obj, setObj] = useState()

console.log(obj) //=> undefined
console.log(obj.length) //=> Uncaught TypeError: Cannot read property 'length' of undefined
console.log(Object.entries(obj)) //=> Uncaught TypeError: Cannot convert undefined or null to object

// versus

const [obj, setObj] = useState({})

console.log(obj) //=> {}
console.log(obj.length) //=> undefined
console.log(Object.entries(obj)) //=> []

obj.length 可能没有多大意义,但这只是一个例子。)

【讨论】:

  • 非常感谢!对我来说更清楚!还有一个问题,什么时候使用带花括号的 useState({}) 更好?我的意思是因为当我们使用 useState([]) 时,我们也可以将对象存储在数组中,对吗?所以好像没必要用useState({})?
  • useState([]) 将初始状态值设置为空数组。 useState({}) 将初始状态值设置为空对象。哪个更合适取决于情况——您希望状态值是数组还是对象?您可能还想要一个布尔值 (useState(true) / useState(false))、一个字符串 (useState('some text')) 或其他东西。取决于你在做什么。
【解决方案2】:

方括号[] 将创建一个数组对象,而使用大括号{} 创建一个普通对象。 这实际上是您希望如何访问数据的问题。你甚至可以将参数设置为useState('')。不使用初始值 useState() 将是 undefined

数组只保存值:

const numbers = [2, 3, 4, 5, 35]
const myNumbers = numbers .map(item=> {
    return item* 2
})

Output
[ 4, 6, 8, 10, 70 ]

数组对象具有键值对。大多数情况下,当我们想在单个变量中创建和存储多个项目的列表时,我们都会使用

const products = [
    { id: '1', name: 'Foo' },
    { id: '2', name: 'bar' }
];
const myProducts = products.map((item, key) => {
    return (
        <tr key={key}>
            <td>{item.id}</td>
            <td>{item.name}</td>
        </tr>
    );
});

此外,如果您使用 ma​​p() {} 迭代数据,这会给您未处理的拒绝(TypeError):products.map 不是函数 因为它是普通对象。

const [products, setProducts] = useState({});

products.map((item) => {
    return item; })

通过使用const [products, setProducts] = useState([]);,您将得到products.length = 0而不会出错。

【讨论】:

    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    • 2017-05-18
    • 2023-03-17
    • 2017-02-13
    相关资源
    最近更新 更多