窗口.使用React和redux的innerHeight

window.innerHeight with React and redux

本文关键字:innerHeight redux 使用 React 窗口      更新时间:2023-09-26

我最近问了一个问题(简单的窗口调整大小反应),以获得这个解决方案的大部分工作,但是现在我正在插入redux,以便我可以重构出web服务调用到一个动作创建者,并通过一个reducer接收数据。(调用是使用json -promise和我使用适当的redux中间件。)

但是现在我似乎不能使用窗口。innerHeight总是返回200:/

的问题是由于有一些状态管理的redux和一些本地的组件(即。"高度")?

提前感谢!

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import GalleryItem from '../components/gallery_item';
import Nav from '../components/nav';
import { fetchImages } from '../actions/index';
export const MF = 'http://www.veilcraft.com';

class Gallery extends Component {

    constructor(props) {
        super(props);
        this.state = {
            images: [],
            height: window.innerHeight
        };
        this.handleResize = this.handleResize.bind(this);
        this.props.fetchImages();
    }
    componentDidMount() {
        window.addEventListener('resize', this.handleResize);
    }
    handleResize(e) {
        this.setState({
            height: window.innerHeight
        });
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
    }
    render() {
        console.log(this.props.height); //outputs 200!
        const galleryItems = this.props.images.map((image) => {
            return <GalleryItem key={image} image={image} height={this.props.height} />
        });
        return (
            <div>
                <Nav />
                <section>
                    {galleryItems}
                </section>
            </div>
        );
    }
}
function mapStateToProps(state) {
    return {
        images: state.images 
    }
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({ fetchImages }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Gallery);

行动:

import jsonp from 'jsonp-promise';
import { MF } from '../containers/gallery'

export const FETCH_IMAGES = 'FETCH_IMAGES';
export function fetchImages() {
    const url = `${MF}/home/`
    const request = jsonp(url, {}).promise;
    return {
        type: FETCH_IMAGES,
        payload: request //return promise        
    };
}

减速机:

import { FETCH_IMAGES } from '../actions/index'
export default function(state = [], action) {
    switch(action.type) {
        case FETCH_IMAGES:
            var images = action.payload.data.images.images.data.map((image) => {
                return image.image;
            });
            return [ ...images, ...state ];
    }
    return state;
}

handleResize中,您正在更新Gallery组件的状态。然后将height传递到GalleryItem作为支柱。

这意味着,在Gallery中,你需要写

console.log(this.state.height);

在GalleryItem中你可以写:

console.log(this.props.height);