简体   繁体   中英

re render on state change with useEffect

App won't re render different data on state change.

State does change in the dev tools but doesn't show on page.

Using button to filter.

export const StoriesPage = () => {
  const [storyIds, setStoryIds] = useState([]);
  const [storyUrl, setStoryUrl] = useState('top');

  useEffect(() => {
    let url = baseUrl;

    storyUrl === 'top'
      ? (url += 'topstories.json')
      : (url += 'newstories.json');

    getStoryIds(url).then(data => setStoryIds(data));
  }, [storyUrl]);

  return (
    <div>
      <div>
        <button onClick={() => setStoryUrl('new')}>New</button>
        <button onClick={() => setStoryUrl('top')}>Top</button>
      </div>
      {storyIds.map((storyId, index) => (
        <Story key={index} storyId={storyId} />
      ))}
    </div>
  );
};

Added a function that clears storyIds before setStoryUrl

  const handleFilter = tag => {
    setStoryIds([]);
    setStoryUrl(tag);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM