反应TypeError:无法读取未定义的属性“ searchField”

时间:2019-03-21 15:15:25

标签: javascript reactjs

TypeError: Cannot read property 'searchField' of undefined
Function.mapStateToProps [as mapToProps]
C:/Users/windw/Desktop/robofriends/src/containers/App.js:11
   8 | 
   9 | const mapStateToProps = state => {
  10 |     return {
> 11 |         searchField: state.searchRobots.searchField
  12 |     }
  13 | }
  14 | 

Code Part

5 个答案:

答案 0 :(得分:1)

很明显searchRobots在状态/存储上不存在或为空。您可以检查以确保您指的是状态正确的searchRobots机器人吗?

答案 1 :(得分:0)

我复制了您的代码,并在此处附上了工作片段。如图所示,您只需要在<SearchBox />中进行更改。我不明白为什么您使用redux。确保仅在需要时才更新全局状态。

希望这会有所帮助!

const CardList = ({ robots }) => {
  return (
    <div>
      {robots.map((user, i) => {
        return (
          <div
            key={i}
            className="bg-light-green dib br3 pa3 ma2 grow bw2 shadow-5"
          >
            <img
              src={`https://robohash.org/${user.id}?200x200`}
              alt="Robot Based On Char."
            />
            <div>
              <h2>{user.name}</h2>
              <p>{user.email}</p>
            </div>
          </div>
        );
      })}
    </div>
  );
};

const SearchBox = ({ searchfield, searchChange }) => {
  return (
    <div>
      <input
        className="pa3 ba b--green bg-lighttest-blue"
        type="search"
        placeholder="search robots"
        onChange={e => searchChange(e)}
      />
    </div>
  );
};

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      robots: [],
      searchfield: ""
    };
  }

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(users => this.setState({ robots: users }));
  }

  onSearchChange = event => {
    this.setState({ searchfield: event.target.value });
  };

  render() {
    const { robots, searchfield } = this.state;
    const filteredRobots = robots.filter(robot => {
      return robot.name.toLowerCase().includes(searchfield.toLowerCase());
    });
    return (
      <div>
        <SearchBox searchChange={this.onSearchChange} />
        <CardList robots={filteredRobots} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.3/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.5.3/react-dom.min.js"></script>

答案 2 :(得分:0)

使用此    searchField:state.searchField  代替 searchField:state.searchRobots.searchField

您的讲师还将指导您删除视频后面的searchRobots。

答案 3 :(得分:0)

对于那些遵循了常规课程但仍然存在此问题的人,您可以做的最简单的黑客就是将reduceRobot中的searchRobots导入到App.js中并进行更改

searchField: state.searchRobots.searchField

searchField: searchRobots(state.searchField)

这对我来说完美而轻松。

答案 4 :(得分:0)

您可能正在学习udemy的课程。那有这个例子。因为我也做到了。如果您不这样做,请不要担心,这是相同的练习,我为您准备了调试程序。当您将redux仅用于一个全局状态时,通过createStore,您无需将变量searchRobots添加到键searchField中,而是应将state.searchField