【问题标题】:setState() in React not updating state onClick Switch (antd)React中的setState()不更新状态onClick Switch(antd)
【发布时间】:2020-11-16 11:55:39
【问题描述】:

当我们点击开关时,状态“valueState”没有更新我不知道为什么??

另外,我有一个“statusValue”类型问题,因为“switch antd”通过 cons 接受布尔值,道具的初始值是数字类型

这是我正在使用的代码:

// 代码//

import React from 'react';
import { Form, Input, Switch } from "antd";
class UpdateCard extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        valueState: this.props.state.status,
    }
}

handleToggle = (checked) => {
    console.log("state",this.state.valueState);
    console.log("checked",checked);
   if (checked === false){
    this.setState({
        valueState:1
      });
   }else {
    this.setState({
        valueState:0
      });
   }
    console.log("handleToggle valueState",this.state.valueState);
  };

  render() {
    const { state } = this.props;

    var statusValue = false;

    if (state.status === 0) { statusValue = true; }
  return (
  <Form id='update-state-form' 
            onFinish={this.onFinish}
            onFinishFailed={this.onFinishFailed}
            initialValues={{
                name: state ? state.name : '',
                status: state ? state.status : false,
                color: state ? state.color :'',
            }}
        >
            <FormItem {...formItemLayout} 
               name="name" 
               label={<IntlMessages id="app.stateName" />} 
               rules={[{ required: true, message: 'Please input the name !' }]} 
            >
                <Input />
            </FormItem>

            <FormItem {...formItemLayout} 
               name="color" 
               label={<IntlMessages id="app.color" />} 
               rules={[{ required: true, message: 'Please input the color !' }]}
            >
                <CirclePicker color={state.color} />
            </FormItem>

            <FormItem {...formItemLayout} 
               name="status" 
               label={<IntlMessages id="app.status" />} 
               rules={[{ required: true, message: 'Please input the status !' }]}
            >
                <Switch  defaultChecked={statusValue}  onClick={this.handleToggle}/>
            </FormItem>
        </Form>
    );
}
}
export default connect(
 null,
  {
     updateStateCardAction,
  }
 )(UpdateCard );

//****************************** 显示console.log *********** *******************//

【问题讨论】:

  • switch 中的 statusValue 是什么?
  • 有两件事,当您调用 this.handleToggle() 时,您没有将任何值作为参数传递,而 setState() 是异步的,因此请记住这一点。 onClick 也只是简单地作为道具传递给 Switch 组件,所以一定要遵循 'antd' 的文档,我个人没有使用过这个库:)

标签: javascript reactjs switch-statement antd setstate


【解决方案1】:

只要我了解您的问题,我觉得您在这里缺少两个主要内容:

  1. statusValue 尚未在该州声明。它应该是状态中的布尔值。从 Ant-Design 的文档中 defaultChecked 属性设置为 false。首先确保将 statusValue 声明为状态变量:

    this.state = {
     valueState: this.props.state.status,
     statusValue:false
    }
    
    ... // and keep state in sync with the UI
    
  2. 那么您必须确保在 onClick 处理程序中传递 statusValue 状态。

     <Switch  
          defaultChecked={this.state.statusValue}  
          onClick={()=>this.handleToggle(this.state.statusValue)}
      />
    

【讨论】:

  • 感谢“Imran”,当我尝试您的解决方案时,我遇到了类型问题,因为 antd 开关接受类型 boolean 我尝试添加“componentDidMount”以在 valueState 等于 1 时将状态“statusValue”修改为 false,但解决方案失败
  • 亲爱的@Wiem:你能告诉我你在哪里仍然面临这个问题吗?我可以浏览一些 antd 的文档,我保证会帮助你 :) 只有你能解释一下你的问题正在尝试从您的代码中实现,尤其是从 Switch 组件中,我很乐意为您提供帮助:)
  • 谢谢亲爱的@Imran 我解决了这个问题非常感谢:)
  • @wiemkhardani 最欢迎亲爱的。如果我的回答以任何方式或形式对您有所帮助,您可以通过单击批准勾选来接受它,以便其他人也发现它有用。这鼓励我帮助越来越多的人:) 谢谢。亲爱的,如果您觉得我的回答有用,请批准它。费 AmaanilLah !!!
【解决方案2】:

您还需要传递值。

<Switch  defaultChecked={statusValue}  onClick={(statusValue) =>this.handleToggle(!statusValue)}/>

【讨论】:

    【解决方案3】:

    这是我的解决方案

    import React, { Component } from 'react';
    import { Switch } from 'antd';
    import './App.css';
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          onCheck: 0,
        };
      }
    
      componentDidUpdate() {
        const { onCheck } = this.state;
        console.log(onCheck);
      }
    
      handleToggle = (checked) => {
        const { onCheck } = this.state;
    
        if (checked) {
          this.setState({ onCheck: 1 });
        } else {
          this.setState({ onCheck: 0 });
        }
      };
    
      render() {
        const { onCheck } = this.state;
        return (
          <div className="App">
            <header className="App-header">
              <Switch defaultChecked={onCheck} onChange={this.handleToggle} />
            </header>
          </div>
        );
      }
    }
    
    export default App;
    .App {
      text-align: center;
    }
    
    .App-header {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: calc(10px + 2vmin);
    }

    【讨论】:

    • 感谢“Max”,但我有一个问题,因为道具“默认检查”接受布尔类型而不是数字类型。此解决方案无法正常工作,因为 switch 的初始值错误。
    • 这对我有用,你能做的是 defaultChecked={onCheck === 1 ?真:假}
    • 我使用了这个解决方案:componentWillMount() { this.props.state.status === 0 ? this.setState({ statusValue: true }) : this.setState({ statusValue: false }) }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多