React – 在存储在ContextProvider中的数组状态中调用所有类实例的函数

huangapple go评论70阅读模式
英文:

React - Calling a function of all class instances in an array state stored in a ContextProvider

问题

I have a provider that stores and adds 'People' to a state. This state is then exposed to the rest of the application. Everything works as expected, however when I get the instances of the classes I am unable to call their function. It returns undefined whenever I try to call it. The code itself does not error, but also doesn't work. Do you have any insight as what might be going wrong?

Person class:

export class Person {
	private name: string;
	constructor() {
		this.name = uniqueNamesGenerator(config);
	}

	getName() {
		return this.name;
	}
}

The provider:

export const PeopleProvider = ({ children }: PropsWithChildren) => {
	const [ people, setPeople ] = useState<IPerson[]>([]);

	const addPerson = () => {
		setPeople([ ...people, new Person() ]);
	};

	const getInstances = (): IPerson[] => {
		return people;
	};

	return (
		<PeopleContext.Provider value={{ addPerson, getInstances }}>
			{children}
		</PeopleContext.Provider>
	);
};

The component:

export const Home = () => {
	const { addPerson, getInstances } = usePeople();

	const add = () => {
		addPerson();
	};

	const getNames = () => {
		const people = getInstances();
		console.log(people);
		console.log(people.forEach(p => p.getName())); // <==== undefined
	};

	return (
		<Grid container>
			<Grid item xs={2}>
				<Typography>Settings</Typography>

				<Button onClick={add}>add</Button>

				<Button onClick={getNames}>get names</Button>
			</Grid>

			<Grid item xs={10}>
				<Typography>Side</Typography>
			</Grid>
		</Grid>
	);
};

When looking in the console, all objects do have a name and a getName function in their prototype. Any idea what might be causing the undefined here?

英文:

I have a provider that stores and adds 'People' to a state. This state is then exposed to the rest of the application. Everything works as expected, however when I get the instances of the classes I am unable to call their function. It returns undefined whenever I try to call it. The code itself does not error, but also doesn't work. Do you have any insight as what might be going wrong?

Person class:

export class Person {
	private name: string;
	constructor() {
		this.name = uniqueNamesGenerator(config);
	}

	getName() {
		return this.name;
	}

}

The provider

export const PeopleProvider = ({ children }: PropsWithChildren) =&gt; {
	const [ people, setPeople ] = useState&lt;IPerson[]&gt;([]);

	const addPerson = () =&gt; {
		setPeople([ ...people, new Person() ]);
	};

	const getInstances = (): IPerson[] =&gt; {
		return people;
	};

	return (
		&lt;PeopleContext.Provider value={{ addPerson, getInstances }}&gt;
			{children}
		&lt;/PeopleContext.Provider&gt;
	);
};

The component

export const Home = () =&gt; {
	const { addPerson, getInstances } = usePeople();

	const add = () =&gt; {
		addPerson();
	};

	const getNames = () =&gt; {
		const people = getInstances();
		console.log(people);
		console.log(people.forEach(p =&gt; p.getName())); // &lt;==== undefined
	};

	return (
		&lt;Grid container&gt;
			&lt;Grid item xs={2}&gt;
				&lt;Typography&gt;Settings&lt;/Typography&gt;

				&lt;Button onClick={add}&gt;add&lt;/Button&gt;

				&lt;Button onClick={getNames}&gt;get names&lt;/Button&gt;
			&lt;/Grid&gt;

			&lt;Grid item xs={10}&gt;
				&lt;Typography&gt;Side&lt;/Typography&gt;
			&lt;/Grid&gt;
		&lt;/Grid&gt;
	);
};

When looking in the console, all objects do have a name and a getName function in their prototype. Any idea what might be causing the undefined here?

答案1

得分: 0

Array.prototype.forEach 返回 undefined

尝试使用 map 方法

console.log(people.map(p => p.getName()))

或者使用 forEach

people.forEach(p => console.log(p.getName()))
英文:

As the docs mentioned https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Array.prototype.forEach returns undefined

Try using map method

console.log(people.map(p =&gt; p.getName()))

or with forEach

people.forEach(p =&gt; console.log(p.getName()))

huangapple
  • 本文由 发表于 2023年5月17日 22:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定