gpt4 book ai didi

javascript - window.innerHeight 与 React 和 redux

转载 作者:行者123 更新时间:2023-12-03 06:00:53 25 4
gpt4 key购买 nike

我最近问了一个问题( Simple window resize react )以使该解决方案的大部分工作正常运行,但是现在我插入 redux,以便我可以重构对操作创建者的 Web 服务调用并通过 reducer 接收数据。 (调用是使用 jsonp-promise 进行的,我正在使用适当的 redux 中间件。)

但是现在我似乎无法使用 window.innerHeight 因为它总是返回 200 :/

问题是否是由于部分状态由 redux 管理而部分状态是组件 native 的(即“高度”)?

非常感谢!

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);

Action :

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
};
}

reducer :

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 作为 prop 传递到 GalleryItem 中。

这意味着,在 Gallery 中,您需要编写

console.log(this.state.height);

在 GalleryItem 中你可以写:

console.log(this.props.height);

关于javascript - window.innerHeight 与 React 和 redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39752224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com