Can not read property 0 of undefined in reactjs

前端 未结 2 1617
抹茶落季
抹茶落季 2020-12-12 07:30

I have an application when user has the possibility to toggle between the components.The idea of the application is next:

  1. User click on add field butt
2条回答
  •  半阙折子戏
    2020-12-12 07:51

    Try to always define a default value, or take care to have exactly that data structure:

    export const Edit = ({ mode, value, keyForm }) => {
      useEffect(() => {
        console.log("value inside edit", value);
      }, []);
      const back = () => {
        mode(true);
      };
      console.log("VALUE: ", value);
      // Default value definitions
      const { names = [] } = value || {};
    
      const { inner = {} } = names[0] || [];
    
      const { first = "" } = inner[keyForm]  || {};
    
      return (
        
    edit mode

    value: {first}

    ); };

    EDIT

    For the toggle issue:

    SubForm.js:

    const DynamicFieldSet = props => {
      const [fieldsOnEdit, setFieldsOnEdit] = useState([]);
    
    
      const toggleSmall = i => {
        setFieldsOnEdit(prev => {
          if(prev.includes(i)) return prev.filter(ea => ea !== i);
    
          return [...prev, i];
        })
      }
    
      console.log("fieldsOnEdit", fieldsOnEdit);
    
      return (
        
          {(fields, { add, remove }) => {
            return (
              
    {fields.map((field, index) => !fieldsOnEdit.includes(index) ? ( ) : ( ) )}
    ); }}
    ); }; export default DynamicFieldSet;

    Edit.js:

    export const Edit = ({ mode, value, keyForm }) => {
    
      useEffect(() => {
        console.log("value inside edit", value);
      }, []);
    
      const { names = [] } = value || {};
    
      const { inner = {} } = names[0] || [];
    
      const { first = "" } = inner[keyForm]  || {};
    
      return (
        
    edit mode

    value: {first}

    ); };

提交回复
热议问题