React-删除请求后组件不会重新呈现

时间:2019-08-21 07:25:18

标签: javascript reactjs fetch

我的问题是,从列表中删除元素后,组件不想重新渲染。当我经过路由到某个子页面然后返回时,项目已被删除,如果我对列表进行排序,则它也消失了。事实是,我不想强​​迫用户刷新网站或进行排序以查看效果。如果我通过

,它就可以正常工作
  

deviceList道具作为“ props.data”而不是“ devices”

(将代码中的位置加粗)。有谁知道如何解决?我仍然对反应挂钩还有些陌生,也许我只是需要调整useEffect更好一些, props.selectedDevices是从redux提取的,只是获取已删除项目的ID,即我的代码:

父母:

function App(props) {
  const [data, setData] = useState("")
  const [filter, setFilter] = useState([])


  useEffect(() => getDeviceDataTotal(), [])

  const getDeviceDataTotal = () => {
    console.log('refresh clicked')
    fetch("http://localhost:4000/device")
      .then(res => res.json())
      .then(res => setData(res))
      .catch(err => {
        throw err;
      });
  };

  const deleteDevices = (e) => {
    console.log('delete clicked')
    props.selectedDevices.map(el => {
      return fetch(`http://localhost:4000/device/delete/${el}`, {
        method: "DELETE"
      })
        .then(res => res.json())
        .then(() => getDeviceDataTotal())
        .catch(err => {
          throw err;
        });
    });
  }

  const filterList = e => {
    let filteredList;
    filteredList = data.filter(el => {
      return el.device_id.includes(searched);
    });
    setFilter(filteredList)
  };


  return (
    <BrowserRouter>
      <MuiThemeProvider theme={createMuiTheme(theme("#96BF1B", "#ffffff"))}>

        <Switch>
          <Route
            exact
            path="/"
            render={() => <Dashboard classes={classes} dataDevice={data} refresh={getDeviceDataTotal} filtered={filter} filterList={filterList} deleteDevices={deleteDevices}/> }
          />
          ......
        </Switch>
      </MuiThemeProvider>
    </BrowserRouter>
  );
}

子组件:

function Dashboard(props) {
  const [selectedSort, setSelectedSort] = useState("1")
  const [devices, setDevices] = useState(props.dataDevice)


  useEffect(() => {
    let isSubscribed = true
    const fetchData = async() => {
      try {
        const res = await fetch("http://localhost:4000/device")
        const response = await res.json()
        if (isSubscribed) {
          setDevices(response)
         }
      } catch (err) {
        console.log(err)
      }
    }

    fetchData()
    return () => isSubscribed = false
  },[])

  useEffect(() => props.refresh() ,[devices])


  useEffect(() => sortDeviceData(), [selectedSort])

  const sortDeviceData = () => {
    switch(selectedSort) {
      case "device":
        (filtered.length ? filtered : dataDevice).sort(function(a,b) {
          return (a.device_id.toUpperCase() < b.device_id.toUpperCase()) ? -1 : (a.device_id.toUpperCase() > b.device_id.toUpperCase()) ? 1 : 0
        })
        setDevices(dataDevice)
        break;
      case "customer":
        (filtered.length ? filtered : dataDevice).sort(function(a,b) {
          return (a.customer.toUpperCase() < b.customer.toUpperCase()) ? -1 : (a.customer.toUpperCase() > b.customer.toUpperCase()) ? 1 : 0
        })
        setDevices(dataDevice)
        break;
      case "server":
        (filtered.length ? filtered : dataDevice).sort(function(a,b) {
          return (a.server.toUpperCase() < b.server.toUpperCase()) ? -1 : (a.server.toUpperCase() > b.server.toUpperCase()) ? 1 : 0
        })
        setDevices(dataDevice)
        break;
      case "creation":
        (filtered.length ? filtered : dataDevice).sort(function(a,b) {
          return (a.createdAt.toUpperCase() < b.createdAt.toUpperCase()) ? -1 : (a.createdAt.toUpperCase() > b.createdAt.toUpperCase()) ? 1 : 0
        })
        setDevices(dataDevice)
        break;
      case "update":
        (filtered.length ? filtered : dataDevice).sort(function(a,b) {
          return (a.updatedAt.toUpperCase() < b.updatedAt.toUpperCase()) ? -1 : (a.updatedAt.toUpperCase() > b.updatedAt.toUpperCase()) ? 1 : 0
        })
        setDevices(dataDevice)
        break;    
      default: 
        return setDevices(dataDevice)
    }
  }


  const { classes, logged, dataDevice, filtered } = props;
  return logged ? (
    <main style={{ display: "flex" }} key={dataDevice}>
      <section className={classes.sectionLeftContainer}>

        <div className={classNames(classes.search, classes.tableBackground)}>
          <InputBase
            placeholder="Search…"
            classes={{
              root: classes.inputRoot,
              input: classes.inputInput
            }}
            inputProps={{ "aria-label": "Search" }}
            onChange={e => props.getSearched(e.target.value)}
          />
          <Button
            variant="outlined"
            className={classes.searchBtn}
            onClick={e => props.filterList(e)}
          >
            Search
          </Button>
          <Button
            variant="outlined"
            className={classes.btnAddDevice}
            onClick={e => {
              if (window.confirm("Are you sure you want to delete this device")) {
                props.deleteDevices(e);
              }
            }}
          >
            <DeleteIcon />
            Delete devices
          </Button>
        </div>
        <div>
          <FormControl className={classes.selectContainer}>

            <Select 
              value={selectedSort} 
              style={{position: 'absolute', right: 0, bottom: 10, width: 150}}
              onChange={e => setSelectedSort(e.target.value)}
              >
              <MenuItem value="1">Default</MenuItem>
              <MenuItem value="device">Device</MenuItem>
              <MenuItem value="customer">User</MenuItem>
              <MenuItem value="server">Server</MenuItem>
              <MenuItem value="creation">Creation date</MenuItem>
              <MenuItem value="update">Update date</MenuItem>
            </Select>
          </FormControl>
        </div>
        <div>
          <DeviceList
            classes={classes}
            **deviceData={devices} if props.data - works well but sorting doesn't work**
            filtered={filtered}
          />
        </div>
      </section>
    </main>
}

2 个答案:

答案 0 :(得分:1)

有多种方法可以强制React组件渲染,但是本质上是相同的。第一种是使用this.forceUpdate(),跳过shouldComponentUpdate

someMethod() {
    // Force a render without state change...
    this.forceUpdate();
}

假设您的组件处于状态,您还可以调用以下内容:

someMethod() {
    // Force a render with a simulated state change
    this.setState({ state: this.state });
}

可能存在更好,更“ React-y”的方法来正确渲染组件,但是如果您迫切希望在命令中渲染组件,则可以。

答案 1 :(得分:0)

一个简单的解决方案是在父组件中设置一个侦听器,该侦听器将在状态改变时触发重新渲染。

父项

const [state, setState] = useState({
    render: false,
    // initial state values...
});

useEffect(() => {
    // fetch an api
    fetch('http://example.com')
    .then(res => res.json())
    .then(data => { 
        //update state using data
        setState(prev => ({...prev, data })) 
     })
     .catch(err => err);    
}, [state.render]);

// trigger function
const refresh = () => setState(prev => ({...prev, render: !prev.render}));

在必要时调用触发函数,例如删除api调用以重新渲染。

// delete function
const onDelete = () => {
    // perform api call
    fetch('http://example.com/id/1', { method: 'DELETE' })
    .then(res => {
        // call refresh to initiate re-render
        return refresh();
    }).catch(err => err);
};