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

时间:2018-05-05 06:47:19

标签: node.js reactjs styled-components nextjs

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

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

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

warning.js?6327:33 Warning: Prop {SRC {1}}

这是我的代码

did not match. Server: "/static/images/testimonials/2.jpg" Client: "/static/images/testimonials/5.png"

相应的风格是

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:

        }
    }
}

2 个答案:

答案 0 :(得分:2)

这就是问题所在。

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

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

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

this.state = {
  currentIndex: 0,
};

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

答案 1 :(得分:0)

使用React 16.8.0中引入的React的useStateuseEffect钩子:

const [selectedImage, setImage] = useState(<defaultImage>);
useEffect(() => { 
    setImage(randomImage());
}, [selectedImage]);