简体   繁体   English

反应:如何更改 map 内拨动开关的状态?

[英]React: How can i change the status of toggle switch inside map?

I have an array named Products.我有一个名为 Products 的数组。 I am showing this products data on the listing page.我在列表页面上显示此产品数据。 Each product in products also has a value called isActive. products 中的每个产品也有一个名为 isActive 的值。 I want to change this isActive value by putting enable/disable switch on listing page.我想通过在列表页面上放置启用/禁用开关来更改这个 isActive 值。 The codes I wrote are as follows, but whenever I click on the toggle, the isActive value returns always false.我写的代码如下,但是每当我点击切换时,isActive 值总是返回 false。 What should I do?我应该怎么办?

我想改变“状态”拨动开关

constructor() {
    super();
    this.state = {
      products: [],
      isActive: null,
      _id: "",
    };
 }
  componentWillMount() {
    // this.setState({isLoading:true});
    const { _id, isActive } = this.state;
    getProducts()
      .then((response) => {
        if (response.data.success) {
          if (response.data.success.data.products) {
            // console.log(response.data.success.data.products);
            let responseData = response.data.success.data.products;
            this.setState({
              products: responseData,
              isLoading: false,
            });
          }
        }
      })
      .catch((error) => {
        console.log(error);
      });
      
  }
  toggleSwitch(_id) {
    const { isActive } = this.state;

    updateProducts({ _id, isActive })
      .then((response) => {
        // console.log(response.data.success.data);
        if (response.data.success.data) {
          toast.success("State have been successfully updated!");
          this.setState((prevState) => ({
            products: prevState.products.map((product) => ({
              ...product,
              isActive: product._id === _id ? !product.isActive : product.isActive,
            })),
          }));
        } else {
          this.setState({
            isLoading: false,
          });
          toast.error("Unable to change!");
        }
      })
      .catch((error) => {
        toast.error("Server Error");
      });

      console.log(isActive);
  }
render() {
    const { isLoading, products } = this.state;
    return (
      <>
{products != null &&
                      products.map((product, key) => {
                        return (
                          <tr key={key} className="text-center">
                            <td scope="col">{key + 1}</td>
                            <td scope=" col">{product.name}</td>
                            <td scope=" col">
                              {product.minUser} - {product.maxUser}
                            </td>
                            <td scope=" col">
                              {/* {product._id} */}
                              {/* {product.isActive.toString()} */}
                              <Switch
                                onChange={() => this.toggleSwitch(product._id)}
                                checked={product.isActive}
                              />
                            </td>
                            <td scope="col" style={{ textAlign: "center" }}>
                              <i
                                onClick={() => this.goToDetail(product)}
                                className="fas fa-sticky-note btn p-1"
                              ></i>
                              <i
                                onClick={() => this.goToEdit(product)}
                                className="fa fa-edit btn p-1"
                              ></i>

                              {/* <Link to={{ pathname: '/dashboard/admin-edit', admin}}>
                                                                <i className="fa fa-edit"></i>
                                                            </Link> */}
                            </td>
                          </tr>
                        );
                      })}
</>
)
}
this.state = {
  products: [],
  isActive: null,
  _id: "",
};

is such a wrong state.是这样一个错误的 state。 As you said, each product has its own isActive state.如您所说,每个产品都有自己的isActive state。 So your state should be as simple as the following所以你的 state 应该像下面这样简单

this.state = {
  products: [],
  isLoading: false,

};

On the other hand, you should not override unrelated values in the state另一方面,您不应覆盖 state 中的无关值

this.setState((prevState) => ({
    products: prevState.products.map((product) => ({
       ...product,
       isActive: product._id === _id ? !product.isActive : product.isActive,
    })),
    isLoading: false
}));

and in the else block, you should not remove products在 else 块中,您不应该删除产品

this.setState((prevState) => ({
   ...prevState,
   isLoading: false,
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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