使用功能组件反应后,事件tigger会更新状态对象

时间:2020-08-23 04:13:34

标签: reactjs

我正在使用useContext挂钩来管理状态,我已经从其他组件的输入滑块字段中删除了handleChange方法,这会更改状态对象,并且该状态用于过滤数据

this is the context API hook component
handleChange is tigger by the other component input price slider
 
 
   const handleChange = (event) => {
    const target = event.target;
    const name = target.name;
    const value = target.value;
    setState(
      {
        ...state,
        [name]: value,
      },
**Part 1
      filterBooks()
    );
  };
  const filterBooks = () => {
    let { books, maxPrice, minPrice, type, category, price } = state;
    let tempBook = [...books];
    price = parseInt(price);
    // console.log(typeof price);
    // console.log(tempBook, price);
    if (type !== "all") {
      tempBook = tempBook.filter((book) => book.type === type);
    }
    tempBook = tempBook.filter((book) => book.price < price);

**Part 2 **

   *code works as expected till here*

    setState({
      ...state,
      sortedBook: tempBook,
    });
    // how to update state in this scenario;
   // as per the docs we can't update state in nested function
  };
  return (
    <ProductContext.Provider value={{ state, handleChange }}>
      {props.children}
    </ProductContext.Provider>
  );
};

export default ProviderContext;```

2 个答案:

答案 0 :(得分:0)

不知道为什么要在setState回调中进行过滤,为什么不只是在初始setState中更新过滤器?

此外,除非您的状态是深层嵌套的,否则您无需将完整状态传递给setState,如果是嵌套的-我会考虑实现redux实现

答案 1 :(得分:0)

我重构了代码,它起作用了

const handleChange = (event) => {
    const target = event.target;
    const name = target.name;
    const value = target.value;
    setFlag(false);

    setState({
      ...state,
      [name]: value,
      sortedBook: [],
    });
    setFlag(true);
  };

  useEffect(() => {
    if (!flag) {
      // console.log("effect called without change - by default");
    } else {
      // console.log("effect called with change ");
      const filterBooks = () => {
        let { books, maxPrice, minPrice, type, category, price } = state;
        let tempBook = [...books];

        if (type !== "all") {
          tempBook = tempBook.filter((book) => book.type === type);
        }
        tempBook = tempBook.filter((book) => book.price < parseInt(price));
        // console.log("from tempbook", tempBook);
        setState({
          ...state,
          sortedBook: tempBook,
        });
      };

      filterBooks();
    }
    // console.log(state);
  }, [state.price, flag]);