Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

javascript - How to re-render component after update hash correctly with useEffect?

I have a component that uses action and repository to request data from rails server and then render it in component, it returns promise, that I've handle and render:

const {loadNews} = props;
const [news, setNews] = useState([]);
const [newsState, setNewsState] = useState('active');
const [pageNum, setPageNum] = useState(1);

where {loadNews} - function, that imports from parent component; Others are state, where:

news - array with news, that map's in different component in render;
newsState- news field state (e.g. 'active', or 'past');
pageNum- pagination state for adding more news in component;

I'm use he next code for update state:

  const locationHashChanged = () => {
    if (window.location.hash === "#state-active") {
      setNewsState('active');
      setPageNum(pageNum);

    }
    else if (window.location.hash == "#state-played") {
      setNewsState('played');
      setPageNum(pageNum);
    }
  }

  window.onhashchange = locationHashChanged;

  const changeHash = () => {
    setNews([]);
    setNewsState('active');
    setPageNum(1)
    loadNews({pageNum, newsState});
  };

  const incrementPage = () => {
    setPageNum(pageNum + 1);
    loadNews({pageNum, newsState});
  };

  useEffect(() => {
    locationHashChanged();
    loadNews({pageNum, newsState})
      .then((response) => {
        const {data} = response;
        setNews(news.concat(data));
      })
      .catch((response) => {
        console.log(response);
      });
  }, [pageNum, newsState]);

If I just use incrementPage function - it works fine - it just add more news with previous array of news and update state. But, I see that state is updated, but array is not.

Expected behaviour - when I click on link in Header component (external component), that changes hash in this component ('active' or 'past' fields) and these news should reload with correct fields(active or past). But now I see no changes. How can I fix it? Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...