Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将项添加到数组的末尾,然后调用函数-React_Javascript_Reactjs - Fatal编程技术网

Javascript 将项添加到数组的末尾,然后调用函数-React

Javascript 将项添加到数组的末尾,然后调用函数-React,javascript,reactjs,Javascript,Reactjs,我不知道如何正确地命名这个。我有一个项目数组,我在其中映射它们,并为每个项目创建一个按钮。单击每个按钮(代表一个类别)时,将加载该类别中的帖子。我在数组的末尾添加了一个额外的项(也将是一个按钮),它将是一个“查看所有”按钮,但它将调用一个不同的函数。到目前为止,该组件类似于: const Posts = ({ state }) => { const [categories, setCategories] = useState([]); const [categoryId, setC

我不知道如何正确地命名这个。我有一个项目数组,我在其中映射它们,并为每个项目创建一个按钮。单击每个按钮(代表一个类别)时,将加载该类别中的帖子。我在数组的末尾添加了一个额外的项(也将是一个按钮),它将是一个“查看所有”按钮,但它将调用一个不同的函数。到目前为止,该组件类似于:

const Posts = ({ state }) => {
  const [categories, setCategories] = useState([]);
  const [categoryId, setCategoryId] = useState();
  const [page, setPage] = useState(1);
  const [posts, setPosts] = useState([]);

  const [allPosts, setAllPosts] = useState([]);

  useEffect(() => {
    fetch(state.source.api + "/wp/v2/categories")
      .then(response => response.json())
      .then(data => {
        setCategories(data);
      })
  }, []);
  console.log(categories);

  useEffect(() => {
    if (categoryId) {
      fetch(state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5")
        .then((response) => response.json())
        .then((data) => {
          setPosts(data);
        });
    }
  }, [categoryId]);

  useEffect(() => {
    if (!categoryId) {
      return;
    }
    let url = state.source.api + "/wp/v2/posts?categories=" + categoryId + "&per_page=5";
    if (page > 1) {
      url += `&page=${page}`;
    }
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        setPosts([...posts, ...data]);
      });
  }, [categoryId, page]);

  useEffect(() => {
    let url = state.source.api + "/wp/v2/posts?per_page=5";
    if (page > 1) {
      url += `&page=${page}`;
    }
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        setAllPosts([...allPosts, ...data]);
      });
  }, [page]);

  const allCategories = categories.map((category, i) => (category))
  allCategories.push("View All");
  console.log(allCategories);

  return (
    <>
      {allCategories.length > 0 ? (
        allCategories.map((category, i) => {
          return (
            <>
              <button className="btn" key={i} onClick={() => {
                setPage(1);
                setPosts([]);
                setCategoryId(category.id);
              }}>{category.name}</button>
              {(category === "View All") && (<button>View all</button>)}
            </>
          )
        })
      ) : (
          <p>Loading...</p>
        )
      }

      <div>
        {posts.length === 0 ? (
          <>
            {allPosts.map((generalPost, i) => {
              return (
                <li key={i}>{generalPost.title.rendered}</li>
              )
            })}
            <button onClick={() => { setPage(page + 1); }}>Load more</button>
          </>
        ) : (
            <>
              <ol>
                {posts.map((post, i) => {
                  // console.log(post.id);
                  return (
                    <li key={i}>{post.title.rendered}</li>
                  )
                })}
              </ol>

              <button onClick={() => { setPage(page + 1); }}>Load more</button>
            </>
          )}
      </div>
    </>
  )
}
const Posts=({state})=>{
const[categories,setCategories]=useState([]);
常量[categoryId,setCategoryId]=useState();
const[page,setPage]=useState(1);
const[posts,setPosts]=useState([]);
const[allPosts,setAllPosts]=useState([]);
useffect(()=>{
获取(state.source.api+“/wp/v2/categories”)
.then(response=>response.json())
。然后(数据=>{
设置类别(数据);
})
}, []);
控制台日志(类别);
useffect(()=>{
if(类别ID){
获取(state.source.api+“/wp/v2/posts?categories=“+categoryId+”&per_page=5”)
.then((response)=>response.json())
。然后((数据)=>{
设置柱(数据);
});
}
},[类别];
useffect(()=>{
如果(!categoryId){
返回;
}
让url=state.source.api+“/wp/v2/posts?categories=“+categoryId+”&每页=5”;
如果(第1页){
url+=`&page=${page}`;
}
获取(url)
.then((response)=>response.json())
。然后((数据)=>{
setPosts([…posts,…data]);
});
},[类别ID,第页];
useffect(()=>{
让url=state.source.api+“/wp/v2/posts?per_page=5”;
如果(第1页){
url+=`&page=${page}`;
}
获取(url)
.then((response)=>response.json())
。然后((数据)=>{
setAllPosts([…allPosts,…data]);
});
},[第页];
const allCategories=categories.map((类别,i)=>(类别))
所有类别。推送(“查看全部”);
console.log(所有类别);
返回(
{allCategories.length>0(
allCategories.map((类别,i)=>{
返回(
{
设置页(1);
设置柱([]);
setCategoryId(category.id);
}}>{category.name}
{(类别===“全部查看”)&&(全部查看)}
)
})
) : (
加载

) } {posts.length==0( {allPosts.map((generalPost,i)=>{ 返回(
  • {generalPost.title.rendered}
  • ) })} {setPage(第+1页);}}>加载更多 ) : ( {posts.map((post,i)=>{ //console.log(post.id); 返回(
  • {post.title.rendered}
  • ) })} {setPage(第+1页);}}>加载更多 )} ) }
    我能够将“查看所有”按钮添加到末尾,但在“查看所有”按钮之前似乎有一个额外的空按钮。我不知道这是怎么回事。它的显示方式如下:

    [书籍][电影][歌曲][]全部查看]


    我在此处将“查看所有”按钮添加到数组的方式是否有问题?

    在原始代码中,您总是渲染一个
    +条件检查以渲染
    查看所有

    allCategories.map((category,i)=>{
    返回(
    {
    设置页(1);
    设置柱([]);
    setCategoryId(category.id);
    }}>{category.name}
    {(类别===“全部查看”)&&(全部查看)}
    )
    })
    
    因此,当
    category==“View All”
    为true时,它还会呈现内容为空的
    元素,因为在这种情况下,
    category.name
    是未定义的

    您需要做的是生成if-else语句或三元表达式,以仅呈现其中一个:

    allCategories.map((category,i)=>{
    返回(
    {(类别==“查看全部”)(
    查看所有
    ) : (
    {
    设置页(1);
    设置柱([]);
    setCategoryId(category.id);
    }}>{category.name}
    )
    )
    })
    
    我明白了,好的。非常感谢你