我正在尝试将存储作为属性传递给AddTodo,但出现错误:无法读取未定义的属性“ todos”

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { connect } from 'react-redux'
import { createStore } from 'redux'

const todo = (state, action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return {
                id: action.id,
                text: action.text
            }
        default:
            return state
    }
}

const todos = (state = [], action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return [
                ...state,
                todo(undefined, action)
            ];
        default:
            return state
    }
}

let store = createStore(todos)


let nextTodoId = 0
const AddTodo = () => {
    let input;

    //this works
    console.log(store.getState())
    //this doesn't
    console.log(this.props.todos)


    return (
        <div>
            <input ref={node => {input = node}}/>
            <button onClick = {() => {
                store.dispatch({
                    type: 'ADD_TODO',
                    id: nextTodoId++,
                    text: input.value
                });
                input.value = ''
            }}>
                Add Todo
            </button>



        </div>
    )
};

store.subscribe(AddTodo)


ReactDOM.render(
    <AddTodo
        todos={store.getState()}
    />,
    document.getElementById('root'));


我有些困惑,为什么在打印this.props.todos时出现错误。我以为我是通过todos作为<AddTodo todos={...}/>中的道具

最佳答案

功能组件的工作方式不同,它们没有this上下文,但是它们的props通过函数的参数传递

要使其工作,只需更改您的addToDos函数调用,如下所示:

const AddTodo = (props) => {
  let input;
  console.log(props.todos);
  return (/* and the rest of your code...*/) ;
};


至于其他内容,正如Arun Ghosh所说,您应该重新访问您的订阅模式,例如这样

store.subscribe(() => {
    ReactDOM.render(
        <AddTodo
           todos={store.getState()}
        />,
        document.getElementById('root'));
});

关于javascript - react :传递属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44748547/

10-17 02:53