将主要组件状态传递给另一个组件错误

时间:2019-11-15 13:51:43

标签: reactjs

我要做的是获取处于主要组件状态的列表,并将其作为道具传递给List组件。

它不起作用,并且我得到“状态”未定义的错误。不知道为什么。 这是我的代码。

import React from 'react';
import List from './components/List';

import './App.css';

function App() {

  state = {
   list: [
     {
       id: 1,
       place: 'Doesn't matter',
       reserved: false
     },

   ]
 } 
 return (
   <div className="App">
    <List  list={this.state.list} />
   </div>
 );
}

export default App;

列出组件List.js

import React from 'react';



function App() {
 return (
   <div className="App">
    <h1>app</h1>
   </div>
 );
}

export default App;

3 个答案:

答案 0 :(得分:1)

在功能组件中,您需要使用useState()函数而不是状态属性

asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.048  INFO 1 --- [nio-6001-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 21 ms
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.086 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Getting user info from: null
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.109 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : HTTP GET 
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.117 DEBUG 1 --- [nio-6001-exec-2] org.springframework.web.HttpLogging      : Accept=[application/json, application/*+json]
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.119  WARN 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : Could not fetch user details: class java.lang.IllegalStateException, Request URI does not contain a valid hostname: 
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.120 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.s.o.r.UserInfoTokenServices      : userinfo returned error: Could not fetch user details
asset-mgmt-v1.1_1  | 2019-11-16 17:52:08.127 DEBUG 1 --- [nio-6001-exec-2] o.s.b.a.audit.listener.AuditListener     : AuditEvent [timestamp=2019-11-16T17:52:08.125Z, principal=access-token, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.BadCredentialsException, message=e2f95093-085c-4b59-90a5-c89fb5d1eccb}]

有关https://reactjs.org/docs/hooks-intro.html的更多信息

答案 1 :(得分:0)

您也可以采用这种方法,我的意思是您可以将App函数转换为可以使用状态的组件类

App.js

import React, { Component } from "react";
import List from "./list";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        place: "Doesn't matter",
        reserved: false
      },
      {
        id: 2,
        place: "Matter",
        reserved: true
      }
    ]
  };

  render() {
    return (
      <div className={"App"}>
        <List list={this.state.list}></List>
      </div>
    );
  }
}

export default App;

然后将您的列表作为功能组件,您只想在其中玩道具

列表组件

import React from "react";
const List = ({ list }) => {
  return (
    <div>
      <ul>
        {list.map(l => (
          <li key={l.id}>{l.place}</li>
        ))}
      </ul>
    </div>
  );
};

export default List;

希望对您有帮助

答案 2 :(得分:0)

这是使用钩子和状态codesandebox

的示例工作示例