【问题标题】:Trying to Update React Context from Form Submit and Trigger List Rerender尝试从表单提交和触发列表重新渲染更新 React 上下文
【发布时间】:2020-03-27 16:35:50
【问题描述】:

我一直在玩 this pen 一段时间作为各种 React 钩子的练习。我想从上下文动态呈现名称列表,并在将新人员对象发布到上下文数组后重新呈现该列表。

看来我已经接近了,因为提交表单会记录更新的peopleNameList,但是上下文似乎没有正确更新,并且表单提交正在使笔崩溃。我错过了一些小问题,还是错过了更大的作文问题?

const {createContext, useState, useEffect, useContext, useReducer} = React;

// https://stackoverflow.com/questions/55757761/handle-an-input-with-react-hooks

// https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react

var dataStore = {
  people: [
         {
            firstName: 'Jim',
            lastName: 'Smith',
            email: 'jims@email.com',
            age: 32,
            job: 'Engineer',
            transportation: 'car'
         },
         {
             firstName: 'Sarah',
             lastName: 'Alton',
             email: 'salton@email.com',
             age: 24,
             job: 'Programmer',
             transportation: 'bike'
         },
        {
             firstName: 'Leslie',
             lastName: 'Leeland',
             email: 'lleeland@woohoo.com',
             age: 24,
             job: 'Teacher',
             transportation: 'Scooter'
         }
    ]
};


// define that context takes an object and an update function
const PeopleContext = createContext();
const PeopleContextProvider = (props) => {
    // dataStore.people as default context state, with a reducer dispatch returned for use with useContext hook to add a new person from the form
    // note you cannot push to a state array because this mutates state directly
    // https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc
    const [peopleStore, addNewPerson] = useReducer((peopleStore, newPerson) =>
     peopleStore.concat(newPerson), dataStore.people);

    return(
        // Context Provider takes a value prop
        <PeopleContext.Provider value={[peopleStore, addNewPerson]}>
            {props.children}
        </PeopleContext.Provider>
    )
}

function RecentPeople(props) {
    // peopleStore equivalent to value prop of PeopleContext provider
    const [peopleStore, addNewPerson] = useContext(PeopleContext);

    const addToPeopleNameList = () => {
        let peopleNameList = [];
        _.map(peopleStore, (i) => {
            let name = `${i.firstName} ${i.lastName}`;
                peopleNameList.push(name);
            return peopleNameList;
        });
        console.log(`peopleNameList: ${peopleNameList}`);
        return(<>
                    {_.map(peopleNameList, (name, i) => <li key={i}>{name}</li>)}
                </>)
    };

    useEffect(() => addToPeopleNameList(), [peopleStore]);

    return(
        <>
        <h3>Recent People</h3>
        <ul>
            {addToPeopleNameList()}
        </ul>
        </>
    );
} // end RecentPeople

function Input(props) {
    let {inputId, value, handleChange } = props;
    let inputLabel = _.startCase(props.inputId);
    return(
        <div class="input-group">
            <label for={inputId}>{inputLabel}</label>
            <input id={inputId} value={value} name={inputId} onChange={handleChange} />
        </div>
    );
};

const inputFields = [ 'firstName', 'lastName', 'email', 'age', 'job', 'transportation' ]

const initialFormState = {
    firstName: '',
    lastName: '',
    email: '',
    age: null,
    job: '',
    transportation: ''
};

function NewUserForm(props) {
    // pass in the reducer function inline to concat existing and new state
    const [inputValues, setInputValues] = useReducer((state, newState) => ({...state, ...newState}), initialFormState);

    const [peopleStore, addNewPerson] = useContext(PeopleContext);

    function handleOnChange(event) {
     const {name, value} = event.target;
            // call the reducer update function, passing in existing formstate with state of current input
            setInputValues({...inputValues, [name]: value });
    }

    function handleSubmit(event) {
        event.preventDefault();
        addNewPerson(inputValues);
        console.log(peopleStore);
        setInputValues({}, {...initialFormState});
    }

    // don't pass event here
    function handleReset(props) {
        setInputValues({}, {...initialFormState});
    }

    return(
        <form id="new-user-form" onSubmit={handleSubmit}>
            {_.map(inputFields, (fieldName) => (<Input key={fieldName} type="text" name={fieldName} inputId={fieldName} handleChange={handleOnChange} />))}

            <button type="submit" value="submit">Add User</button>

            <button type="reset" style={{"marginLeft": "20px"}} onClick={handleReset}>Reset Form</button>
        </form>
    );
} // form


function App() {
    return(
        <PeopleContextProvider>
        <div id="main">
            <h1>Hello!</h1>
            <NewUserForm />
            <RecentPeople />
        </div>
        </PeopleContextProvider>
    );
};

ReactDOM.render(<App />, document.getElementById('App'));

【问题讨论】:

  • 先修复你的代码:codesandbox.io/s/…
  • _. not defined 来自于在 Codepen 中导入 lodash。您需要在 CodeSandbox 中导入 lodash 才能复制。
  • 还有人想看吗? :)

标签: javascript reactjs forms react-hooks


【解决方案1】:

似乎主要的罪魁祸首是 useEffect 不能直接返回渲染列表函数,并且需要将其包裹在括号中以限定函数范围。通过其他一些名称更改和小调整,更正的笔在这里,现在显示上下文的调度函数被正确调用,列表组件监听更改并重新呈现列表。可能可以在那里进行一些优化以仅显示不同的项目。

https://codepen.io/smallreflection/pen/yLyLQge?editors=1011

useEffect(() => { renderPeopleNameList() }, [peopleStoreContext]);

【讨论】:

    猜你喜欢
    • 2019-09-15
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多