Javascript ReactJS:Uncaught ReferenceError:[函数]未定义,2017年7月

Javascript ReactJS:Uncaught ReferenceError:[函数]未定义,2017年7月,javascript,json,reactjs,Javascript,Json,Reactjs,尝试将JSON文件转换为数组,然后从中随机选择5项 我认为问题在于ImageContainer.js底部的render/return语句,但我是ReactJS n00b,所以它可能是任何东西 非常感谢您的帮助或建议 控制台错误 compiled.js:31562 Uncaught ReferenceError: selectImages is not defined at ImageContainer.render (compiled.js:31562) at compiled.js:2

尝试将JSON文件转换为数组,然后从中随机选择5项

我认为问题在于ImageContainer.js底部的render/return语句,但我是ReactJS n00b,所以它可能是任何东西

非常感谢您的帮助或建议

控制台错误

compiled.js:31562 Uncaught ReferenceError: selectImages is not defined
  at ImageContainer.render (compiled.js:31562)
  at compiled.js:20195
  at measureLifeCyclePerf (compiled.js:19475)
  at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (compiled.js:20194)
  at ReactCompositeComponentWrapper._renderValidatedComponent (compiled.js:20221)
  at ReactCompositeComponentWrapper.performInitialMount (compiled.js:19761)
  at ReactCompositeComponentWrapper.mountComponent (compiled.js:19657)
  at Object.mountComponent (compiled.js:4009)
  at ReactDOMComponent.mountChildren (compiled.js:24150)
  at ReactDOMComponent._createInitialChildren (compiled.js:21126)
ImageContainer.js-从.JSON文件中提取img信息,随机选择5进行渲染

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
  constructor(props) {
    super(props);

    this.numImages = 5;

    this.state = {
      data: []
    };
  }

  componentDidMount() {
    $.ajax({
      url: '../app/data/namegame-data.json',
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error('#GET Error', status, err.toString());
      }.bind(this)
    });
  }

  shuffleArray(array) {
    let i = array.length - 1;
    for (; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      const temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }

  selectImages({ data }) {
    const shuffledImages = shuffleArray(images);
    return (
      shuffledImages.map((data, idx) => {
        for (let i = 0; i < this.numImages; i++) {
            if (this.state.data.length > 0) {
                return <Image key={idx} name={data.name} src={data.src} />;
            }
        }
      })
    );
  }

  render() {
    return {selectImages};
  }
}
我认为“这”是错误的地方;):

selectImages是ImageContainer类的一部分, 这意味着函数的作用域在这个类中,所以它应该是这个。selectImages

在渲染中,您可以调用selectimages

render() {
    return {this.selectImages()}; <-- its a function so u should call it as a function
}
关于你的另一个问题

shuffleArray() {
  (array) <-- u are mutating the data from the state, when u passed it to the function, u should only change state with setState.

     use another shuffle function where u dont mutate the data ,use concat or es6 spread operator [ ...data ] etc .
关于数据->

u should parse the json setstate({ data: JSON.parse(data) }) or setstate({ data: $.parseJSON(data) }); 
我必须说,将jquery与react结合使用并不是我应该推荐的,jquery主要用于dom操作,react使用其虚拟dom,并且仅为ajax请求包含整个jquery库是一种浪费

尝试“fetch”这里是ImageContainer.js的更新(主要)工作版本,它包含了Danillo的更改并解决了随后的数组问题。这些问题主要与遗漏“这个”和“这个州”有关

ImageContainer.js

{
  ...
  "dependencies": {
    "json-loader": "^0.5.4",
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  },
  "devDependencies": {
    "css-loader": "^0.28.4",
    "extract-text-webpack-plugin": "^2.1.2",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^2.2.0",
    "webpack-dev-server": "^2.5.0"
  }
}
import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);

        this.numImages = 5;

        this.state = {
          data: []
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    shuffleArray(array) {
      let i = array.length - 1;
      for (; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }

    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data);
      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}
从“React”导入React;
从“react dom”导入react dom;
从“/Image”导入{Image};
导出类ImageContainer扩展React.Component{
建造师(道具){
超级(道具);
这个.numImages=5;
此.state={
数据:[]
};
}
组件willmount(){
$.ajax({
url:“./app/data/namegame data.json”,
数据类型:“json”,
成功:功能(数据){
this.setState({data:data});
}.绑定(此),
错误:函数(xhr、状态、错误){
console.error('#GET error',status,err.toString());
}.绑定(此)
});
}
shuffleArray(阵列){
设i=array.length-1;
对于(;i>0;i--){
常数j=数学楼层(数学随机()*(i+1));
常数温度=数组[i];
数组[i]=数组[j];
数组[j]=温度;
}
返回数组;
}
选择图像(){
const shuffleImage=this.shufflearlay(this.state.data);
返回(
ShuffleImage.map((数据,idx)=>{
for(设i=0;i
我很快在00:45:D更改了您的代码,但尝试类似的方法,在我的另一个答案中解释。德国劳埃德船级社

import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          numImages: 5
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          type: 'get',
          success: function(data) {
            this.setState({data: JSON.parse(data) });
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    randomPickFromArray() {
      // * as asked: " Attempting to turn a JSON file into an array, then randomly selecting 5 items from it. "

      // lets not shuffle, and just random pick 5 items from array,
      const { data, numImages } = this.state;
      const arr = [];
      for (let i = 0; i < numImages; i++) {
        arr.push(data[Math.floor(Math.random() * data.length)]);
      }
      return arr;
    }

    selectImages() {
      const shuffledImages = this.randomPickFromArray();
      return shuffledImages.map((item, idx) => <Image key={idx} name={item.name} src={item.src} />);
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}
从“React”导入React;
从“react dom”导入react dom;
从“/Image”导入{Image};
导出类ImageContainer扩展React.Component{
建造师(道具){
超级(道具);
此.state={
数据:[],
数字图像:5
};
}
组件willmount(){
$.ajax({
url:“./app/data/namegame data.json”,
数据类型:“json”,
键入:“get”,
成功:功能(数据){
this.setState({data:JSON.parse(data)});
}.绑定(此),
错误:函数(xhr、状态、错误){
console.error('#GET error',status,err.toString());
}.绑定(此)
});
}
randomPickFromArray(){
//*如所问:“尝试将JSON文件转换为数组,然后从中随机选择5项。”
//让我们不要洗牌,从数组中随机选取5个项目,
const{data,numImages}=this.state;
常数arr=[];
for(设i=0;i);
}
render(){
返回(
{this.selectImages()};
)
}
}

感谢您的快速回复!肯定再近几步。现在的错误是:Uncaught TypeError:除了进行更改并添加一些“this”前缀外,无法读取undefined的属性'length'。我将componentDidMount()更改为componentWillMount(),这会加载,但ajax调用没有成功。进一步读取表明componentDidMount()是正确的,但是JSON可能没有被解析成任何有用的东西——继续对此进行攻击。
shuffleArray() {
  (array) <-- u are mutating the data from the state, when u passed it to the function, u should only change state with setState.

     use another shuffle function where u dont mutate the data ,use concat or es6 spread operator [ ...data ] etc .
    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data); <-- u dont have to pass this.state.data, to the function ,it is accessable within shufflarray -> const shuffledImages = this.shuffleArray();

      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }
$.getJSON('whateverjson file.json').done(function(response) {
    console.log("Success");
}).fail(function() {
    console.log("Error");
});
u should parse the json setstate({ data: JSON.parse(data) }) or setstate({ data: $.parseJSON(data) }); 
import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);

        this.numImages = 5;

        this.state = {
          data: []
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    shuffleArray(array) {
      let i = array.length - 1;
      for (; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
      return array;
    }

    selectImages() {
      const shuffledImages = this.shuffleArray(this.state.data);
      return (
          shuffledImages.map((data, idx) => {
            for (let i = 0; i < this.numImages; i++) {
                return <Image key={idx} name={this.state.data.name} src={this.state.data.src} />;
            }
          })
      );
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}
import React from 'react';
import ReactDOM from 'react-dom';
import { Image } from './Image';

export class ImageContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          numImages: 5
        };
    }

    componentWillMount() {
      $.ajax({
          url: './app/data/namegame-data.json',
          dataType: 'json',
          type: 'get',
          success: function(data) {
            this.setState({data: JSON.parse(data) });
          }.bind(this),
          error: function(xhr, status, err) {
            console.error('#GET Error', status, err.toString());
          }.bind(this)
        });
    }

    randomPickFromArray() {
      // * as asked: " Attempting to turn a JSON file into an array, then randomly selecting 5 items from it. "

      // lets not shuffle, and just random pick 5 items from array,
      const { data, numImages } = this.state;
      const arr = [];
      for (let i = 0; i < numImages; i++) {
        arr.push(data[Math.floor(Math.random() * data.length)]);
      }
      return arr;
    }

    selectImages() {
      const shuffledImages = this.randomPickFromArray();
      return shuffledImages.map((item, idx) => <Image key={idx} name={item.name} src={item.src} />);
    }

    render() {
        return (
            <div>
                {this.selectImages()};
            </div>
        )
    }
}