我有很多类,我希望用户键入一个名称,他将获得一个特定对象(类)的同名实例.我用这段代码简化了它:
public class Animal {...}
public class lion extends Animal{...}
public class zebra extends Animal{...} // and so on for a lot of animals
String name = input from user
Animal something = new Animal(instance of the input name)
Run Code Online (Sandbox Code Playgroud)
在最后一行,我实际上想将字符串名称转换为类名的实例.有什么办法吗?会有很多动物,所以我不想写很多开关案例:"如果输入等于狮子"或斑马或蛇或......
Calendar将以初始值(events)开头的日历组件(命名).Calendar将只获得一些事件(不需要添加查询)并将重新呈现.我设法分别做了每个,但不是两个:对于(1):仅在数据准备就绪时渲染,而不是使用状态,则无法完成(2).对于(2):使用状态但不能完成(1).
下面的代码很简单:
import React, { Component, PropTypes } from 'react';
import gql from 'graphql-tag';
import { graphql } from 'react-apollo';
const requestsQuery = gql`query requestsQuery { ... }
class MainComponent extends Component {
constructor() {
super();
this.state = {
events: []
};
// here i want to know when the data that apollo fetched is ready
// and then i will create events (using the data)
// and then:
// this.setState({events: events}); …Run Code Online (Sandbox Code Playgroud) 假设我有一个获取数组的组件,我想做一些逻辑:
const MyComponent = ({ myArray = [] }) => {
console.log("infinite rendering");
const [prop, setProp] = useState([])
useEffect(() => {
setProp(myArray.map(x => x + 1))
}, [myArray])
return <div />
}
Run Code Online (Sandbox Code Playgroud)
https://codesandbox.io/s/x3kq907r5z
问题是我得到了一个无限循环。
我可以通过删除默认值({ myArray })并检查数组来修复错误if (Array.isArray(myArray)) setProp(...)
但我很难理解:使用钩子对道具(数组/对象/等)进行任何类型的操作的最佳方法是什么?