简体   繁体   中英

Javascript property is shows undefined when used as default state in React

I fetched some content via useEffect to be used as a default state in my app. Please see code below:

const id = props.match.params.id;
const classes = UseStyles();
const dispatch = useDispatch();

useEffect(() => dispatch(fetchCategories()), []);
const categories = useSelector((state) => state).generalReducer.category;

useEffect(() => dispatch(fetchBusinessDetail(id)), []);
const business = useSelector((state) => state).generalReducer.businessDetail;
console.log(business);

console.log(business.name);
let defaultState = {
  name: business.name,
  description: business.description,
  url: business.url,
  phone: business.phone,
  address: business.address,
  category_id: [],
  email: business.email,
  image: "",
};

const [formState, setFormState] = useState(defaultState);
console.log(formState);

console.log(business) and console.log(business.name) gave expected results however, console.log(formState) gives undefined values like this:

{
  // ...
  image: "";
  name: undefined;
  phone: undefined;
  url: undefined;
}

How do I fix this please?

Using useState(initialState) , initialState will be the value on initial render .

During the initial render, the returned state (state) is the same as the value passed as the first argument (initialState).

Because you fetching the defaultState , its initial value is what you get from redux store :

// business values are values from redux store
let defaultState = {name: business.name, description: business.description, url:business.url, phone:business.phone, address: business.address, category_id: [], email:business.email, image:''  };

Usually, you update the state after you done fetching :

const businessSelector = state => state.generalReducer.businessDetail;

const business = useSelector(businessSelector);

// Fetch and update `business` above.
useEffect(() => dispatch(fetchBusinessDetail(id)), []);

// `business` get new values and update the form.
useEffect(() => {
  setFormState(business);
}, [business]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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