猿问

每次执行函数并且我的反应状态发生变化时过滤数组

我正在开发一个与播放列表有关的项目,所以我想要执行的是,每当单击播放列表中的一首歌曲时,就应该查看附加到该歌曲的图像。所以,我的代码是这样的......


const Component = () => {

  const value = useContext(DataContext);


  const [data, setData] = useState(null);

  const [currentData, setCurrentData] = useState(null);


  useEffect(() => {

    const url =

      "https://52-90-82-235.maverickmaven.com/geotourdata/json.cfm?h=-107,37,s,en,3A771765";


    const currentValue = value;


    axios({

      method: "get",

      url,

      responseType: "stream",

    }).then((response) => {

      let features = response.data.features.filter((elem) => {

        return elem.type === "Feature";

      });


      setData(features);


      const currentDatafile = data?.filter((data) => {

        return data?.assets[0].audio === value;

      });

      setCurrentData(currentDatafile);

    });

  }, [setCurrentData]);

};


所以,这段代码的作用是返回包含图片的数组,但问题是它只过滤一次,即使我点击另一首歌曲,它也只会重复返回相同的值,而且我每次点击时都需要它进行过滤在歌曲上(即执行该函数)。


我尝试同时过滤和映射,但没有成功。或者也许我的语法写得不够好。


牛魔王的故事
浏览 123回答 2
2回答

千万里不及你

将这些行移至新的 useEffect 挂钩。设置数据后会触发useEffect(() => {  const currentDatafile = data?.filter((item) => {    return item.assets[0].audio === value;  });  setCurrentData(currentDatafile)},[data])

人到中年有点甜

您不应该每次都从远程源重新获取数据。我已将其包装在自定义挂钩中,在这里(以及自定义获取器函数以使测试/模拟更容易)。然后,您不应该将选定的对象保持在状态中,除非您需要在内部修改它(在这种情况下,无论如何您都应该将其复制到状态原子中);相反,只需持有 ID 即可。function fetchTourData() {&nbsp; return fetch('https://52-90-82-235.maverickmaven.com/geotourdata/json.cfm?h=-107,37,s,en,3A771765')&nbsp; &nbsp; .then(response => response.json())&nbsp; &nbsp; .then(data => data.features.filter((elem) => elem.type === 'Feature'));}function useTourData() {&nbsp; const [data, setData] = React.useState(null);&nbsp; React.useEffect(() => {&nbsp; &nbsp; fetchTourData().then(setData);&nbsp; }, [setData]);&nbsp; return data;}const Component = () => {&nbsp; const tourData = useTourData();&nbsp; const [selectedId, setSelectedId] = React.useState(null);&nbsp; const selectedTour = (tourData || []).find(t => t.id === selectedId);&nbsp; if (tourData === null) {&nbsp; &nbsp; return <div>Loading</div>&nbsp; }&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; Selected: {JSON.stringify(selectedTour || "nothing")}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <ul>&nbsp; &nbsp; &nbsp; &nbsp; {tourData.map(t => <li key={t.id}><a href="#" onClick={() => setSelectedId(t.id)}>{t.name}</a></li>)}&nbsp; &nbsp; &nbsp; </ul>&nbsp; &nbsp; </div>&nbsp; );};ReactDOM.render(<Component />, document.getElementById("root"));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script><div id="root"></div>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答