在父级之前反应子项渲染?

时间:2018-07-30 00:04:43

标签: javascript reactjs state

我正在跟Udemy上的Stephen Grider的Simple Redux Simple Starter一起关注。基本上,我所需要做的就是将YouTube api中的视频数量返回给DOM。在video_list.js中调用{props.videos.length}时,在下面图片的输入正下方应显示5,但始终返回0。是先渲染子道具,还是子状态未正确更新?请注意,第一个控制台日志来自video_list,第二个控制台日志来自App类中的index.js。

Index.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';
const API_KEY = 'XXXXXXXXXXXXXXX';

class App extends Component {
    constructor(props) {
        super(props);

        this.state = { videos: [] };

        YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
            console.log(videos);
            this.setState = ({ videos }); 
        });
    }

    render() {
        return (
            <div>
                <VideoList videos={this.state.videos} />
            </div>
        );
    }
}

ReactDOM.render(<App />, document.querySelector('.container'));

video_list.js

import React from 'react';

const VideoList = (props) => {
    console.log(props)
    return (
        <ul className='col-md-4 list-group'>
            {props.videos.length}
        </ul>
    }
};

export default VideoList;

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在覆盖setState函数。删除=即可调用它。

YTSearch({key: API_KEY, term: 'surfboards'}, (videos) => {
  this.setState({ videos }); 
});