1

我已经尝试了很多东西,但似乎无法理解为什么 setTypes 不会更新“类型”数组?

import { useState, useEffect } from 'react';
import { PostList } from './post-list';
import * as api from '../utils/api';

export const PostSelector = (props) => {
  const [posts, setPosts]     = useState([]);
  const [loading, setLoading] = useState(false);
  const [type, setType]       = useState('post');
  const [types, setTypes]     = useState([]);
  
  const fetchTypes = async () => {
    setLoading(true);
    const response = await api.getPostTypes();
    delete response.data.attachment;
    delete response.data.wp_block;
    const postTypes = response.data;
    console.log(response.data); // {post: {…}, page: {…}, case: {…}}
    setTypes(postTypes);
    console.log(types); // []

    // Why types remain empty??
  }

const loadPosts = async (args = {}) => {
  const defaultArgs = { per_page: 10, type };
  const requestArgs = { ...defaultArgs, ...args };
  

  requestArgs.restBase = types[requestArgs.type].rest_base; // Cannot read property 'rest_base' of undefined
  
  const response = await api.getPosts(requestArgs);
  console.log(response.data);
}

useEffect(() => {
  fetchTypes();
  loadPosts();
}, []);

  return (
    <div className="filter">
      <label htmlFor="options">Post Type: </label>
      <select name="options" id="options">
        { types.length < 1 ? (<option value="">loading</option>) : Object.keys(types).map((key, index) => <option key={ index } value={ key }>{ types[key].name }</option> ) }
      </select>
    </div>
  );
}

请查看 console.log 并注意不同的响应。

我要做的是加载类型列表,在本例中为“帖子”、“页面”和“案例”,然后根据当前“类型”呈现帖子列表。默认类型是“发布”。

如果我将 [types] 添加到 useEffect. 我终于得到了值,但组件不停地呈现。

感谢大家的意见。很多人都指出了这个问题,因为我们设置状态并不意味着它会立即设置,因为它是异步的。

那我们如何解决这个问题呢?不管是什么原因,我们如何完成它?如果我们不知道它何时可用,我们如何在任何时间点使用我们的状态并根据我们的状态执行计算?我们如何确保我们等待我们需要的任何东西,然后使用我们期望的值?

4

5 回答 5

1

对于任何来到这里并且无法设置/更新 useState 数组的人,您需要使用扩展运算符 (...) 而不仅仅是数组,例如“[...initState]”而不是“initState”

 //initialise
  const initState: boolean[] = new Array(data.length).fill(false);
  const [showTable, setShowTable] = useState<boolean[]>([...initState]);

  // called from an onclick to update
  const updateArray = (index: number) => {
    showTable[index] = !showTable[index];
    setShowTable([...showTable]);
  };
于 2021-05-18T08:39:19.020 回答
0

似乎 useState 是异步的,并且在调用它后不会立即更新值。

在此处查看相同的案例

于 2020-02-19T02:29:31.150 回答
0

您已将您的类型声明为一个数组,但您正在将一个字典字典传递给它。尝试这个:

const [types, setTypes]     = useState({});

你也不需要打电话

loadPosts()

因为 useState 钩子会重新渲染你的组件,只更新需要的内容。

于 2020-02-19T03:01:12.920 回答
0

好的,简短的回答是由于闭包

这不是因为asynchronous其他答案说的!!!


解决方法(☞゚ヮ゚)☞</h3>

console.log您可以像这样通过atreturn函数检查更改。

return (
    <div> Hello World! 
      {
        console.log(value) // this will reference every re-render
      } 
    </div>
  );

或创建一个新的 useEffectvalue作为依赖项,如下所示

 React.useEffect(() => {
    console.log(value); // this will reference every value is changed
  }, [value]);

function App() {
  const [value, Setvalue] = React.useState([]);
  
  React.useEffect(() => {
    Setvalue([1, 2, 3]);
    console.log(value); // this will reference to value at first time
  }, []);
  
  return (
    <div> Hello World! 
      {
        console.log(value) // this will reference every re-render
      } 
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

<div id="app"></div>

阅读此处更详细:useState 设置方法未立即反映更改

于 2021-05-18T08:49:00.270 回答
0

useState的 setTypes 是一个异步函数,因此更改不会立即生效。你可以useEffect用来检查是否有任何变化

useEffect(()=>{
    const defaultArgs = { per_page: 10, type };
    const requestArgs = { ...defaultArgs, ...args };
    requestArgs.restBase = types;
    console.log("types updated",types)
},[types])

您可以删除loadPosts,因为现在 useEffect 将在类型更改时运行

于 2020-02-19T02:43:49.200 回答