React:html代码段中的初始状态值

时间:2018-04-03 14:22:39

标签: reactjs redux

import React, {Component} from 'react';
import {createStore} from 'redux'
import 'bootstrap/dist/css/bootstrap.css';
import './App.css'

let initialState = [{
    type: 'INCREMENT',
    payload: {
        name: "Andrew",
        lastName: 'Radkevich'
    }
}];

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT' :
            return action.payload;
        case 'DECREMENT':
            return action.payload;
        default :
            return state
    }
};


let store = createStore(reducer);

class App extends Component {
    render() {
        console.log(store.getState().name,'name')
        return <ChildContainer
            value={`${store.getState().name} ${store.getState().lastName}`}
            onClickIncrement={
                () => {
                    store.dispatch({
                        type: 'INCREMENT',
                        payload: {
                            name: "Andrew",
                            lastName: 'Radkevich'
                        }
                    })
                }
            }
            onClickDecrement={
                () => {
                    store.dispatch({
                        type: 'DECREMENT',
                        payload: {
                            name: "Igor",
                            lastName: 'Radkevich'
                        }
                    })
                }
            }
        />
    }
}


class ChildContainer extends Component {
    render() {
        return <div>
       // this part of code here 
            <h1 id={'id'}>{this.props.value}</h1>
            <button onClick={this.props.onClickIncrement}>+</button>
            <button onClick={this.props.onClickDecrement}>-</button>
        </div>
    }
}
const render = () => {
    document.getElementById('id').innerText = `${store.getState().name} ${store.getState().lastName}`;
};
store.subscribe(render);
export default App

嗨,那里)我有一个关于如何在加载页面之前加载初始状态的问题?

{this.props.value} - 在这部分代码中(我在上面的代码段中添加了注释),我想在页面加载时获取值,但是我得到了未定义的内容(见下文) )。为什么会这样?如果你也能解释我

enter image description here

1 个答案:

答案 0 :(得分:0)

这样做的:

....
return <ChildContainer value={`${store.getState().payload[0].name} ${store.getState().payload[0].lastName}`}
...

应该修复。

你拯救国家的方式真的很奇怪。此外,您的代码结构不是最好的。我建议你参加一个小型的react / redux初学者课程/教程,如this