简体   繁体   English

反应 JSON 映射数据。 尝试从映射函数传递 setState 变量不会在渲染时获得最新状态

[英]React JSON mapped data. Trying to pass a setState variable from mapped function will not get the latest state on render

I'm working on a React SPA and trying to render JSON data with a filter.我正在研究 React SPA 并尝试使用过滤器呈现 JSON 数据。 I have several containers that each have a class value.我有几个容器,每个容器都有一个类值。 When clicking on a container, I am trying to pass a value to a setState.单击容器时,我试图将值传递给 setState。 When stepping out of the map function, however, I cannot get the new state change to update.但是,当退出地图功能时,我无法更新新的状态更改。

I'm assuming that the render state isn't getting updated for the state.我假设渲染状态没有为该状态更新。

import React, { Component } from "react";
import ListData from "../data/list.json";

class Levels extends Component {
  constructor(props) {
    super(props);
    this.state = { newFilter: "" };
    this.onClick = this.setFilter.bind(this);
  }

  setFilter = e => {
    console.log(e); //This returns the correct class.
    this.setState({ newFilter: e }); //This will not update
  };

  render() {
    console.log(this.state.newFilter); //This just returns the initial state of ''
    const activeTab = this.props.keyNumber;
    let levelFilter = ListData.filter(i => {
      return i.level === activeTab;
    });
    let renderLevel = levelFilter.map((detail, i) => {
      let short_desc;
      if ((detail.short || []).length === 0) {
        short_desc = "";
      } else {
        short_desc = <p>{detail.short}</p>;
      }

      return (
        <div
          className={`kr_sItem ${detail.class}`}
          data-value={detail.class}
          onClick={() => this.onClick(detail.class)}
          value={detail.class}
          key={i}
        >
          <h1>{detail.title}</h1>
          {short_desc}
          <img src={`${detail.img}`} />
        </div>
      );
    });

    console.log(this.state.newFilter);

    return (
      <div id="kr_app_wrapper">
        <div id="lOneWrapper">{renderLevel}</div>
        <div id="lTwoWrapper"></div>
      </div>
    );
  }
}

export default Levels;

Here is the code calling in the Component:这是在组件中调用的代码:

import React, {Component} from 'react';
import Levels from './components/levels2';

import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";
import LevelTwo from "./levelTwo";

class LevelOne extends Component{
    render(){

        return(
            <div id="lOneWrapper">
            <NavLink to='/Level2'><Levels keyNumber={1} /></NavLink>
            </div>
        )
    }
}
export default LevelOne;

Edit: As pointed out in the comments, binding an arrow function is pointless but it wouldn't cause the error here, so there must be something else going on in some other part of your code.编辑:正如评论中所指出的,绑定一个箭头函数是没有意义的,但它不会在这里导致错误,所以在你的代码的其他部分肯定有其他事情发生。

The problem is you are trying to bind an arrow function that doesn't have an implicit this .问题是您正在尝试绑定一个没有隐式this的箭头函数。 Either call setFilter directly (no need to bind this with arrow functions) or change your setFilter function to a regular function:要么直接调用setFilter (无需将this与箭头函数绑定)或将setFilter函数更改为常规函数:

class Levels extends Component{
     constructor(props){
    super(props);
    this.state = {newFilter: ''};
    this.onClick = this.setFilter.bind(this);
  }


  setFilter(e) {
    console.log(e); //This returns the correct class.
    this.setState({newFilter: e}); //This will not update

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM