為何使用Redux?

以剛剛的todo list app的 state 物件管理為範例來說,

如果不使用Redux,則需要把剛剛的initialState放到global變數 window物件下

如下所示:

const NoteApp = ()=>{

   const id = window.state.nextNoteId;

   window.state.notes[id]={

         id,

        content: ' '

   };

  window.state.nextNoteId++;

  renderApp();

}

const NoteApp = ({notes}) =>(

   <div>

         <ul className="note-list">

         {

             Object.keys(notes).map(id=>

                    <li className="note-list-item" key={id}>{id}</li>

             ))

        }

       </ul>

   </div>

);

const renderApp = () =>{

    ReactDOM.render(

            <NoteApp notes={windows.state.notes}/>,

            document.getElementById('root')

    );

};

renderApp();

以下是範例 code: http://codepen.io/yuanyu/pen/pPVBPY

從以上的範例來看起來似乎 不用Redux也沒有甚麼問題?

以下開始加入更多state,假設需要處理onLoading state

如下:

const onAddNote = () =>{

   window.state.onLoading = true;

   renderApp();

   api.createNote()

        .then((note)=> {

                 window.state.onLoading = false;

                window.state.notes[id] = note;

                renderApp();

        });

};

使用這種方式就可能會造成以下幾點錯誤:

const ARCHIVE_TAG_ID = 0 ;

const onAddTAg = ( noteId, tagId ) => {

window.state.onLoading = true;

// Whoops, forgetting to render here !

// For quick local server, we might not notice

api.addTag(noteId, tageId)

      .then(()=>{

        window.state.onLoading = false;

        window.statee.tapMapping[tagId] = noteId;

           if(ARCHIVE_TAG_ID){

           // Whoops, some naming bug here, Probably from a

           // rogue search and replace

           // we test that archive page that nobady really uses

           window.state.archived = window.state.archive || {};

           window.state.archived[noteId] = window.state.notes[noteId];

           delete window.state.notes[noteId];

           }

           renderApp();

        });

};

然而,如果加了一些邏輯修正 ,在長久之後將沒人知道為何要這樣管理state,如下

const SomeEvilComponent = () => {

<button onClick={()=> window.state.pureEvil = true} >Do Evil</button>

};

在加了一大堆類似上述邏輯後,在經過一段時間後,

將會遇到以下幾種可能問題:

  1. Rendering can be kicked off from anywhere

results matching ""

    No results matching ""