jeudi 9 juillet 2020

TypeError: Cannot read property 'has' of undefined

I got an error when I tried to use two checkboxs at the same time in Reactjs. And I got this error message:

TypeError: Cannot read property 'has' of undefined
FormContainer.render
src/container/formcontainer.component.js:268
  265 | <label className="form-check-label">
  266 |   <input
  267 |     type="checkbox"
> 268 |     checked={this.state.departRelated.isExternal.has}
      | ^  269 |     onChange={this.onChangeExternal}
  270 |     className="form-check-input"
  271 |   />

Below is my application:

class FormContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      newPost: {
        title: "",
        type: "",
        depart: "",
        selectedList: [],
        description: ""
      },
      departRelated: {
 
        isExternal: {
          has: false,
          name: "External"
        },
        isInternal: {
          have: false,
          name: "Internal"
        }
      };

onChangeExternal = () => {
    this.setState(initialState => ({
      departRelated: {
        isExternal: {
          has: !this.state.departRelated.isExternal.has
        }
      }
    }));
  };

  onChangeInternal = () => {
    this.setState(initialState => ({
      departRelated: {
        isInternal: {
          have: !this.state.departRelated.isInternal.have
        }
      }
    }));
  };

return (
<div className="form-check">
          <label className="form-check-label">
            <input
              type="checkbox"
              checked={this.state.departRelated.isExternal.has}
              onChange={this.onChangeExternal}
              className="form-check-input"
            />
            External
          </label>
        </div>
        <div className="form-check">
          <label className="form-check-label">
            <input
              type="checkbox"
              checked={this.state.departRelated.isInternal.have}
              onChange={this.onChangeInternal}
              className="form-check-input"
            />
            Internal
          </label>
          {/* <p>this box is {msg}.</p> */}
        </div>
)

I only show related parts here. I have to keep both has(have) and name in departRelated because I want to store the name (with has(have) value == true) in my database later. I comment External part, Internal part works and vice versa. But, when I apply both External and Internal parts, it fails. Anyone knows why???




Aucun commentaire:

Enregistrer un commentaire