在React Component中的setState中使用Math.random时,组件的呈现不正确

时间:2022-08-01 20:12:15

The intention is to display an item from a list of objects but on every page refresh, the item should be randomly chosen from the list. Here, Testimonials is the list and I want to display any random item from this list. If I use a constant, it works fine. When I use, the random function, it does not display proper image with its associated item message.

目的是显示对象列表中的项目,但在每次刷新页面时,应从列表中随机选择该项目。在这里,Testimonials是列表,我想显示此列表中的任何随机项。如果我使用常量,它可以正常工作。当我使用随机函数时,它不会显示带有相关项目消息的正确图像。

I use React 16, Next.js, styled components as the tech.

我使用React 16,Next.js,样式组件作为技术。

The problem is in rendering of Employees section. The console displays a warning as

问题在于呈现Employees部分。控制台显示警告

warning.js?6327:33 Warning: Propsrcdid not match. Server: "/static/images/testimonials/2.jpg" Client: "/static/images/testimonials/5.png"

warning.js?6327:33警告:Propsrcdid不匹配。服务器:“/ static/images/testimonials/2.jpg”客户:“/ static/images/testimonials/5.png”

Here is the piece of my code

这是我的代码

import {Component} from 'react';

import Row from '../../../common-util/row';
import Col from '../../../common-util/col';

import {Container, Content, Image, StyledCol, Statement, Title, Designation, Heading, Arrow} from './styles';

const Testimonials = [{
    name: 'ACX',
    role: 'XYZ',
    image: '/static/images/testimonials/1.jpeg',
    message: 'KL DSAD E'
}, {
    name: 'HJK',
    role: 'Growth Hacker',
    image: '/static/images/testimonials/2.jpg',
    message: 'JKLASD ASDA'
}, {
    name: 'ZXCV',
    role: 'Product Manager',
    image: '/static/images/testimonials/3.jpg',
    message: 'KKK'
}, {
    name: 'UIP',
    role: 'Data Integrity',
    image: '/static/images/testimonials/4.JPG',
    message: 'LOPO'
}, {
    name: 'NMa',
    role: 'Sales Evangelist',
    image: '/static/images/testimonials/5.png',
    message: 'KK D D D'
}];

export default class Employees extends Component {

    constructor(props) {
        super(props);
        this.state = {
            currentIndex: parseInt((Math.random()*10))%5,
        };
    }

    render() {
        let {currentIndex} = this.state;
        return (
            <Container>
                <Content>
                    <Title>Our employees say...</Title>
                </Content>
                <Row>
                    <Col xs={1} sm={1} md={2} lg={2}>
                        <Arrow className={currentIndex === 0 ? 'disabled' : ''} onClick={this.handleClick.bind(this, 'DECREMENT')}>{'<'}</Arrow>
                    </Col>
                    <Col xs={10} sm={10} md={8} lg={8}>{this.currentItem(currentIndex)}</Col>
                    <Col xs={1} sm={1} md={2} lg={2}>
                        <Arrow className={currentIndex === Testimonials.length - 1 ? 'disabled' : ''} onClick={this.handleClick.bind(this, 'INCREMENT')}>{'>'}</Arrow>
                    </Col>
                </Row>
            </Container>
        );
    }

    currentItem(currentIndex) {
        const item = Testimonials[currentIndex];
        return (
            <Row>
                <StyledCol xs={4} md={4} lg={3}>
                    <Image src={item.image} alt={item.name} />
                </StyledCol>
                <Col xs={8} md={8} lg={9}>
                    <Statement>{item.message}</Statement>
                    <Heading className='font-Bold'>{item.name},</Heading>
                    <Designation className='font-DemiBold'>{item.role}</Designation>
                </Col>
            </Row>
        );
    }

    handleClick(type: string) {
        let {currentIndex} = this.state;
        switch (type) {
            case 'DECREMENT':
                this.setState({
                    currentIndex: currentIndex - 1
                });
                break;
            case 'INCREMENT':
                this.setState({
                    currentIndex: currentIndex + 1
                });
                break;
            default:

        }
    }
}

The corresponding style is

相应的风格是

import styled from 'styled-components';

import Col from '../../../common-util/col';
import Grid from '../../../common-util/grid';
import H4 from '../../../common-util/headers/h4';
import H5 from '../../../common-util/headers/h5';

export const Container = styled(Grid)`
    padding-bottom: 20px;
`;

export const Content = styled.div`
    display: flex;
    flex-flow: row wrap;
    width: 100%;
    justify-content: center;
    margin-bottom: 20px;
`;

export const Title = styled.h1`
    font-size: 42px;
    line-height: 1.0;
    letter-spacing: -0.3px;
    text-align: justify;
    font-weight: 500;
`;

export const Image = styled.img`
    width: 100%;
`;

export const Statement = styled.p`
    padding: 15px 20px;
    background: url(/static/images/svg/top-left-bg.svg) top left no-repeat, url(/static/images/svg/bottom-right-bg.svg) bottom right no-repeat;
    background-size: 20px;
    line-height: 2.3;
    letter-spacing: -0.2px;
    font-size: 16px;
    margin: 0
`;

export const Heading = H4.extend`
    color: #4990e2;
    text-align: left;
    font-weight: bold;
    line-height: 1.2;
    margin-bottom: 5px;
    margin-left: 20px;
`;

export const Designation = H5.extend`
    text-align: left;
    font-weight: 600;
    line-height: 1.22;
    letter-spacing: -0.2px;
    margin-top: 0;
    margin-left: 20px;
`;

export const Arrow = styled.div`
    margin: auto;
    color: grey;
    font-size: 20px;
    font-weight:lighter;
    cursor: pointer;
    &:hover {
        font-size: 22px;
    }

    &.disabled {
        pointer-events: none;
        &:hover {
            font-size: 20px;
        }
    }
`;

export const StyledCol = Col.extend`
    margin: auto;
`;

1 个解决方案

#1


2  

That's the problem.

那就是问题所在。

this.state = {
   currentIndex: parseInt((Math.random()*10))%5,
};

This will be invoked on a server and in the browser causing a mismatch in rendered markup.

这将在服务器和浏览器中调用,导致渲染标记不匹配。

You could fix that by making sure random will only be called in a browser:

你可以通过确保随机只在浏览器中调用来解决这个问题:

this.state = {
  currentIndex: 0,
};

componentDidMount(){
  this.setState({ currentIndex: parseInt((Math.random()*10))%5 })
}

#1


2  

That's the problem.

那就是问题所在。

this.state = {
   currentIndex: parseInt((Math.random()*10))%5,
};

This will be invoked on a server and in the browser causing a mismatch in rendered markup.

这将在服务器和浏览器中调用,导致渲染标记不匹配。

You could fix that by making sure random will only be called in a browser:

你可以通过确保随机只在浏览器中调用来解决这个问题:

this.state = {
  currentIndex: 0,
};

componentDidMount(){
  this.setState({ currentIndex: parseInt((Math.random()*10))%5 })
}