Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从react js中的父组件状态更新子组件下拉列表中的选项值?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何从react js中的父组件状态更新子组件下拉列表中的选项值?

Javascript 如何从react js中的父组件状态更新子组件下拉列表中的选项值?,javascript,reactjs,Javascript,Reactjs,我有一个需求,比如,在父组件中,我从api获取数据,并将该数据数组传递给DataTable子组件,以表格式显示。在这种情况下,我需要为每个列显示一个下拉列表,并且选项是预定义的(不需要动态值)。我只需要,当用户选择下拉值时,它应该在父组件状态下更新,并填充在特定下拉组件中选择的值 value={props.schema.length > 0 ? props.schema[index]['Type'] : null} - > this line giving me the error

我有一个需求,比如,在父组件中,我从api获取数据,并将该数据数组传递给DataTable子组件,以表格式显示。在这种情况下,我需要为每个列显示一个下拉列表,并且选项是预定义的(不需要动态值)。我只需要,当用户选择下拉值时,它应该在父组件状态下更新,并填充在特定下拉组件中选择的值

value={props.schema.length > 0 ? props.schema[index]['Type'] : null}  - > this line giving me the error and wroking fine when console.log() outside return.



console.log(props.schema.length > 0 ? props.schema[0]['Type'])  -> it is working
这是我试过的

用于存储下拉列表值的父组件::

   let [schema, setSchema] = useState([])

      const handleChange = (event, index) => {
        setSchema([
          ...schema,
          {
            Name: event.target.name,
            Type: event.target.value
          }
        ]);
    };
要显示数据的父组件内的DataTable组件:

                <Container>
                    <DataTable
                        data={data}
                        meta_data={meta_data}
                        handleChange={handleChange}
                        schema={schema}
                    />
                </Container>
当我在索引中检索该数组的类型字段时。它给出了未定义的“Type”,但我实际上是在控制台从外部返回子组件时工作的

value={props.schema.length > 0 ? props.schema[index]['Type'] : null}  - > this line giving me the error and wroking fine when console.log() outside return.



console.log(props.schema.length > 0 ? props.schema[0]['Type'])  -> it is working
如何解决


任何建议都很好。

在返回语句上方放置一个控制台,如

console.log(props.schema[index]['Type'])

试着从我的猜测中找出哪里出了问题。键(filteredData[0])可能比props.schema[index]有移动数组值。因此它可能会抛出错误。

useState钩子具有以下形式:

const [state, setState] = useState(initialState);
书中写道:

如果使用前一状态计算新状态,则可以将函数传递给setState。函数将接收上一个值,并返回更新后的值

这意味着您应该更改此选项:

setSchema([
      ...schema,
      {
        Name: event.target.name,
        Type: event.target.value
      }
    ]);
为此:

setSchema((prevSchema) => {
  return [
      ...prevSchema,
      {
        Name: event.target.name,
        Type: event.target.value
      }
    ])
 };
setSchema((prevSchema) => {
  return [
      ...prevSchema,
      {
        Name: event.target.name,
        Type: event.target.value
      }
    ])
 };